xref: /sqlite-3.40.0/src/btree.c (revision 2e27d28f)
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       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
3985         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
3986           rc = saveCursorPosition(p);
3987           if( rc!=SQLITE_OK ){
3988             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
3989             break;
3990           }
3991         }
3992       }else{
3993         sqlite3BtreeClearCursor(p);
3994         p->eState = CURSOR_FAULT;
3995         p->skipNext = errCode;
3996       }
3997       btreeReleaseAllCursorPages(p);
3998     }
3999     sqlite3BtreeLeave(pBtree);
4000   }
4001   return rc;
4002 }
4003 
4004 /*
4005 ** Rollback the transaction in progress.
4006 **
4007 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4008 ** Only write cursors are tripped if writeOnly is true but all cursors are
4009 ** tripped if writeOnly is false.  Any attempt to use
4010 ** a tripped cursor will result in an error.
4011 **
4012 ** This will release the write lock on the database file.  If there
4013 ** are no active cursors, it also releases the read lock.
4014 */
4015 int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4016   int rc;
4017   BtShared *pBt = p->pBt;
4018   MemPage *pPage1;
4019 
4020   assert( writeOnly==1 || writeOnly==0 );
4021   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4022   sqlite3BtreeEnter(p);
4023   if( tripCode==SQLITE_OK ){
4024     rc = tripCode = saveAllCursors(pBt, 0, 0);
4025     if( rc ) writeOnly = 0;
4026   }else{
4027     rc = SQLITE_OK;
4028   }
4029   if( tripCode ){
4030     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4031     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4032     if( rc2!=SQLITE_OK ) rc = rc2;
4033   }
4034   btreeIntegrity(p);
4035 
4036   if( p->inTrans==TRANS_WRITE ){
4037     int rc2;
4038 
4039     assert( TRANS_WRITE==pBt->inTransaction );
4040     rc2 = sqlite3PagerRollback(pBt->pPager);
4041     if( rc2!=SQLITE_OK ){
4042       rc = rc2;
4043     }
4044 
4045     /* The rollback may have destroyed the pPage1->aData value.  So
4046     ** call btreeGetPage() on page 1 again to make
4047     ** sure pPage1->aData is set correctly. */
4048     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4049       int nPage = get4byte(28+(u8*)pPage1->aData);
4050       testcase( nPage==0 );
4051       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4052       testcase( pBt->nPage!=nPage );
4053       pBt->nPage = nPage;
4054       releasePage(pPage1);
4055     }
4056     assert( countValidCursors(pBt, 1)==0 );
4057     pBt->inTransaction = TRANS_READ;
4058     btreeClearHasContent(pBt);
4059   }
4060 
4061   btreeEndTransaction(p);
4062   sqlite3BtreeLeave(p);
4063   return rc;
4064 }
4065 
4066 /*
4067 ** Start a statement subtransaction. The subtransaction can be rolled
4068 ** back independently of the main transaction. You must start a transaction
4069 ** before starting a subtransaction. The subtransaction is ended automatically
4070 ** if the main transaction commits or rolls back.
4071 **
4072 ** Statement subtransactions are used around individual SQL statements
4073 ** that are contained within a BEGIN...COMMIT block.  If a constraint
4074 ** error occurs within the statement, the effect of that one statement
4075 ** can be rolled back without having to rollback the entire transaction.
4076 **
4077 ** A statement sub-transaction is implemented as an anonymous savepoint. The
4078 ** value passed as the second parameter is the total number of savepoints,
4079 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4080 ** are no active savepoints and no other statement-transactions open,
4081 ** iStatement is 1. This anonymous savepoint can be released or rolled back
4082 ** using the sqlite3BtreeSavepoint() function.
4083 */
4084 int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4085   int rc;
4086   BtShared *pBt = p->pBt;
4087   sqlite3BtreeEnter(p);
4088   assert( p->inTrans==TRANS_WRITE );
4089   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4090   assert( iStatement>0 );
4091   assert( iStatement>p->db->nSavepoint );
4092   assert( pBt->inTransaction==TRANS_WRITE );
4093   /* At the pager level, a statement transaction is a savepoint with
4094   ** an index greater than all savepoints created explicitly using
4095   ** SQL statements. It is illegal to open, release or rollback any
4096   ** such savepoints while the statement transaction savepoint is active.
4097   */
4098   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4099   sqlite3BtreeLeave(p);
4100   return rc;
4101 }
4102 
4103 /*
4104 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4105 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4106 ** savepoint identified by parameter iSavepoint, depending on the value
4107 ** of op.
4108 **
4109 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
4110 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4111 ** contents of the entire transaction are rolled back. This is different
4112 ** from a normal transaction rollback, as no locks are released and the
4113 ** transaction remains open.
4114 */
4115 int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4116   int rc = SQLITE_OK;
4117   if( p && p->inTrans==TRANS_WRITE ){
4118     BtShared *pBt = p->pBt;
4119     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4120     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4121     sqlite3BtreeEnter(p);
4122     if( op==SAVEPOINT_ROLLBACK ){
4123       rc = saveAllCursors(pBt, 0, 0);
4124     }
4125     if( rc==SQLITE_OK ){
4126       rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4127     }
4128     if( rc==SQLITE_OK ){
4129       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4130         pBt->nPage = 0;
4131       }
4132       rc = newDatabase(pBt);
4133       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
4134 
4135       /* The database size was written into the offset 28 of the header
4136       ** when the transaction started, so we know that the value at offset
4137       ** 28 is nonzero. */
4138       assert( pBt->nPage>0 );
4139     }
4140     sqlite3BtreeLeave(p);
4141   }
4142   return rc;
4143 }
4144 
4145 /*
4146 ** Create a new cursor for the BTree whose root is on the page
4147 ** iTable. If a read-only cursor is requested, it is assumed that
4148 ** the caller already has at least a read-only transaction open
4149 ** on the database already. If a write-cursor is requested, then
4150 ** the caller is assumed to have an open write transaction.
4151 **
4152 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4153 ** be used for reading.  If the BTREE_WRCSR bit is set, then the cursor
4154 ** can be used for reading or for writing if other conditions for writing
4155 ** are also met.  These are the conditions that must be met in order
4156 ** for writing to be allowed:
4157 **
4158 ** 1:  The cursor must have been opened with wrFlag containing BTREE_WRCSR
4159 **
4160 ** 2:  Other database connections that share the same pager cache
4161 **     but which are not in the READ_UNCOMMITTED state may not have
4162 **     cursors open with wrFlag==0 on the same table.  Otherwise
4163 **     the changes made by this write cursor would be visible to
4164 **     the read cursors in the other database connection.
4165 **
4166 ** 3:  The database must be writable (not on read-only media)
4167 **
4168 ** 4:  There must be an active transaction.
4169 **
4170 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4171 ** is set.  If FORDELETE is set, that is a hint to the implementation that
4172 ** this cursor will only be used to seek to and delete entries of an index
4173 ** as part of a larger DELETE statement.  The FORDELETE hint is not used by
4174 ** this implementation.  But in a hypothetical alternative storage engine
4175 ** in which index entries are automatically deleted when corresponding table
4176 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4177 ** operations on this cursor can be no-ops and all READ operations can
4178 ** return a null row (2-bytes: 0x01 0x00).
4179 **
4180 ** No checking is done to make sure that page iTable really is the
4181 ** root page of a b-tree.  If it is not, then the cursor acquired
4182 ** will not work correctly.
4183 **
4184 ** It is assumed that the sqlite3BtreeCursorZero() has been called
4185 ** on pCur to initialize the memory space prior to invoking this routine.
4186 */
4187 static int btreeCursor(
4188   Btree *p,                              /* The btree */
4189   int iTable,                            /* Root page of table to open */
4190   int wrFlag,                            /* 1 to write. 0 read-only */
4191   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
4192   BtCursor *pCur                         /* Space for new cursor */
4193 ){
4194   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
4195   BtCursor *pX;                          /* Looping over other all cursors */
4196 
4197   assert( sqlite3BtreeHoldsMutex(p) );
4198   assert( wrFlag==0
4199        || wrFlag==BTREE_WRCSR
4200        || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4201   );
4202 
4203   /* The following assert statements verify that if this is a sharable
4204   ** b-tree database, the connection is holding the required table locks,
4205   ** and that no other connection has any open cursor that conflicts with
4206   ** this lock.  */
4207   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
4208   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4209 
4210   /* Assert that the caller has opened the required transaction. */
4211   assert( p->inTrans>TRANS_NONE );
4212   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4213   assert( pBt->pPage1 && pBt->pPage1->aData );
4214   assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4215 
4216   if( wrFlag ){
4217     allocateTempSpace(pBt);
4218     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
4219   }
4220   if( iTable==1 && btreePagecount(pBt)==0 ){
4221     assert( wrFlag==0 );
4222     iTable = 0;
4223   }
4224 
4225   /* Now that no other errors can occur, finish filling in the BtCursor
4226   ** variables and link the cursor into the BtShared list.  */
4227   pCur->pgnoRoot = (Pgno)iTable;
4228   pCur->iPage = -1;
4229   pCur->pKeyInfo = pKeyInfo;
4230   pCur->pBtree = p;
4231   pCur->pBt = pBt;
4232   pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
4233   pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
4234   /* If there are two or more cursors on the same btree, then all such
4235   ** cursors *must* have the BTCF_Multiple flag set. */
4236   for(pX=pBt->pCursor; pX; pX=pX->pNext){
4237     if( pX->pgnoRoot==(Pgno)iTable ){
4238       pX->curFlags |= BTCF_Multiple;
4239       pCur->curFlags |= BTCF_Multiple;
4240     }
4241   }
4242   pCur->pNext = pBt->pCursor;
4243   pBt->pCursor = pCur;
4244   pCur->eState = CURSOR_INVALID;
4245   return SQLITE_OK;
4246 }
4247 int sqlite3BtreeCursor(
4248   Btree *p,                                   /* The btree */
4249   int iTable,                                 /* Root page of table to open */
4250   int wrFlag,                                 /* 1 to write. 0 read-only */
4251   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
4252   BtCursor *pCur                              /* Write new cursor here */
4253 ){
4254   int rc;
4255   if( iTable<1 ){
4256     rc = SQLITE_CORRUPT_BKPT;
4257   }else{
4258     sqlite3BtreeEnter(p);
4259     rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4260     sqlite3BtreeLeave(p);
4261   }
4262   return rc;
4263 }
4264 
4265 /*
4266 ** Return the size of a BtCursor object in bytes.
4267 **
4268 ** This interfaces is needed so that users of cursors can preallocate
4269 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
4270 ** to users so they cannot do the sizeof() themselves - they must call
4271 ** this routine.
4272 */
4273 int sqlite3BtreeCursorSize(void){
4274   return ROUND8(sizeof(BtCursor));
4275 }
4276 
4277 /*
4278 ** Initialize memory that will be converted into a BtCursor object.
4279 **
4280 ** The simple approach here would be to memset() the entire object
4281 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
4282 ** do not need to be zeroed and they are large, so we can save a lot
4283 ** of run-time by skipping the initialization of those elements.
4284 */
4285 void sqlite3BtreeCursorZero(BtCursor *p){
4286   memset(p, 0, offsetof(BtCursor, iPage));
4287 }
4288 
4289 /*
4290 ** Close a cursor.  The read lock on the database file is released
4291 ** when the last cursor is closed.
4292 */
4293 int sqlite3BtreeCloseCursor(BtCursor *pCur){
4294   Btree *pBtree = pCur->pBtree;
4295   if( pBtree ){
4296     int i;
4297     BtShared *pBt = pCur->pBt;
4298     sqlite3BtreeEnter(pBtree);
4299     sqlite3BtreeClearCursor(pCur);
4300     assert( pBt->pCursor!=0 );
4301     if( pBt->pCursor==pCur ){
4302       pBt->pCursor = pCur->pNext;
4303     }else{
4304       BtCursor *pPrev = pBt->pCursor;
4305       do{
4306         if( pPrev->pNext==pCur ){
4307           pPrev->pNext = pCur->pNext;
4308           break;
4309         }
4310         pPrev = pPrev->pNext;
4311       }while( ALWAYS(pPrev) );
4312     }
4313     for(i=0; i<=pCur->iPage; i++){
4314       releasePageNotNull(pCur->apPage[i]);
4315     }
4316     unlockBtreeIfUnused(pBt);
4317     sqlite3_free(pCur->aOverflow);
4318     /* sqlite3_free(pCur); */
4319     sqlite3BtreeLeave(pBtree);
4320   }
4321   return SQLITE_OK;
4322 }
4323 
4324 /*
4325 ** Make sure the BtCursor* given in the argument has a valid
4326 ** BtCursor.info structure.  If it is not already valid, call
4327 ** btreeParseCell() to fill it in.
4328 **
4329 ** BtCursor.info is a cache of the information in the current cell.
4330 ** Using this cache reduces the number of calls to btreeParseCell().
4331 */
4332 #ifndef NDEBUG
4333   static void assertCellInfo(BtCursor *pCur){
4334     CellInfo info;
4335     int iPage = pCur->iPage;
4336     memset(&info, 0, sizeof(info));
4337     btreeParseCell(pCur->apPage[iPage], pCur->ix, &info);
4338     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
4339   }
4340 #else
4341   #define assertCellInfo(x)
4342 #endif
4343 static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4344   if( pCur->info.nSize==0 ){
4345     int iPage = pCur->iPage;
4346     pCur->curFlags |= BTCF_ValidNKey;
4347     btreeParseCell(pCur->apPage[iPage],pCur->ix,&pCur->info);
4348   }else{
4349     assertCellInfo(pCur);
4350   }
4351 }
4352 
4353 #ifndef NDEBUG  /* The next routine used only within assert() statements */
4354 /*
4355 ** Return true if the given BtCursor is valid.  A valid cursor is one
4356 ** that is currently pointing to a row in a (non-empty) table.
4357 ** This is a verification routine is used only within assert() statements.
4358 */
4359 int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4360   return pCur && pCur->eState==CURSOR_VALID;
4361 }
4362 #endif /* NDEBUG */
4363 int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4364   assert( pCur!=0 );
4365   return pCur->eState==CURSOR_VALID;
4366 }
4367 
4368 /*
4369 ** Return the value of the integer key or "rowid" for a table btree.
4370 ** This routine is only valid for a cursor that is pointing into a
4371 ** ordinary table btree.  If the cursor points to an index btree or
4372 ** is invalid, the result of this routine is undefined.
4373 */
4374 i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4375   assert( cursorHoldsMutex(pCur) );
4376   assert( pCur->eState==CURSOR_VALID );
4377   assert( pCur->curIntKey );
4378   getCellInfo(pCur);
4379   return pCur->info.nKey;
4380 }
4381 
4382 /*
4383 ** Return the number of bytes of payload for the entry that pCur is
4384 ** currently pointing to.  For table btrees, this will be the amount
4385 ** of data.  For index btrees, this will be the size of the key.
4386 **
4387 ** The caller must guarantee that the cursor is pointing to a non-NULL
4388 ** valid entry.  In other words, the calling procedure must guarantee
4389 ** that the cursor has Cursor.eState==CURSOR_VALID.
4390 */
4391 u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4392   assert( cursorHoldsMutex(pCur) );
4393   assert( pCur->eState==CURSOR_VALID );
4394   getCellInfo(pCur);
4395   return pCur->info.nPayload;
4396 }
4397 
4398 /*
4399 ** Given the page number of an overflow page in the database (parameter
4400 ** ovfl), this function finds the page number of the next page in the
4401 ** linked list of overflow pages. If possible, it uses the auto-vacuum
4402 ** pointer-map data instead of reading the content of page ovfl to do so.
4403 **
4404 ** If an error occurs an SQLite error code is returned. Otherwise:
4405 **
4406 ** The page number of the next overflow page in the linked list is
4407 ** written to *pPgnoNext. If page ovfl is the last page in its linked
4408 ** list, *pPgnoNext is set to zero.
4409 **
4410 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
4411 ** to page number pOvfl was obtained, then *ppPage is set to point to that
4412 ** reference. It is the responsibility of the caller to call releasePage()
4413 ** on *ppPage to free the reference. In no reference was obtained (because
4414 ** the pointer-map was used to obtain the value for *pPgnoNext), then
4415 ** *ppPage is set to zero.
4416 */
4417 static int getOverflowPage(
4418   BtShared *pBt,               /* The database file */
4419   Pgno ovfl,                   /* Current overflow page number */
4420   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
4421   Pgno *pPgnoNext              /* OUT: Next overflow page number */
4422 ){
4423   Pgno next = 0;
4424   MemPage *pPage = 0;
4425   int rc = SQLITE_OK;
4426 
4427   assert( sqlite3_mutex_held(pBt->mutex) );
4428   assert(pPgnoNext);
4429 
4430 #ifndef SQLITE_OMIT_AUTOVACUUM
4431   /* Try to find the next page in the overflow list using the
4432   ** autovacuum pointer-map pages. Guess that the next page in
4433   ** the overflow list is page number (ovfl+1). If that guess turns
4434   ** out to be wrong, fall back to loading the data of page
4435   ** number ovfl to determine the next page number.
4436   */
4437   if( pBt->autoVacuum ){
4438     Pgno pgno;
4439     Pgno iGuess = ovfl+1;
4440     u8 eType;
4441 
4442     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
4443       iGuess++;
4444     }
4445 
4446     if( iGuess<=btreePagecount(pBt) ){
4447       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
4448       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
4449         next = iGuess;
4450         rc = SQLITE_DONE;
4451       }
4452     }
4453   }
4454 #endif
4455 
4456   assert( next==0 || rc==SQLITE_DONE );
4457   if( rc==SQLITE_OK ){
4458     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
4459     assert( rc==SQLITE_OK || pPage==0 );
4460     if( rc==SQLITE_OK ){
4461       next = get4byte(pPage->aData);
4462     }
4463   }
4464 
4465   *pPgnoNext = next;
4466   if( ppPage ){
4467     *ppPage = pPage;
4468   }else{
4469     releasePage(pPage);
4470   }
4471   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
4472 }
4473 
4474 /*
4475 ** Copy data from a buffer to a page, or from a page to a buffer.
4476 **
4477 ** pPayload is a pointer to data stored on database page pDbPage.
4478 ** If argument eOp is false, then nByte bytes of data are copied
4479 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
4480 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
4481 ** of data are copied from the buffer pBuf to pPayload.
4482 **
4483 ** SQLITE_OK is returned on success, otherwise an error code.
4484 */
4485 static int copyPayload(
4486   void *pPayload,           /* Pointer to page data */
4487   void *pBuf,               /* Pointer to buffer */
4488   int nByte,                /* Number of bytes to copy */
4489   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
4490   DbPage *pDbPage           /* Page containing pPayload */
4491 ){
4492   if( eOp ){
4493     /* Copy data from buffer to page (a write operation) */
4494     int rc = sqlite3PagerWrite(pDbPage);
4495     if( rc!=SQLITE_OK ){
4496       return rc;
4497     }
4498     memcpy(pPayload, pBuf, nByte);
4499   }else{
4500     /* Copy data from page to buffer (a read operation) */
4501     memcpy(pBuf, pPayload, nByte);
4502   }
4503   return SQLITE_OK;
4504 }
4505 
4506 /*
4507 ** This function is used to read or overwrite payload information
4508 ** for the entry that the pCur cursor is pointing to. The eOp
4509 ** argument is interpreted as follows:
4510 **
4511 **   0: The operation is a read. Populate the overflow cache.
4512 **   1: The operation is a write. Populate the overflow cache.
4513 **
4514 ** A total of "amt" bytes are read or written beginning at "offset".
4515 ** Data is read to or from the buffer pBuf.
4516 **
4517 ** The content being read or written might appear on the main page
4518 ** or be scattered out on multiple overflow pages.
4519 **
4520 ** If the current cursor entry uses one or more overflow pages
4521 ** this function may allocate space for and lazily populate
4522 ** the overflow page-list cache array (BtCursor.aOverflow).
4523 ** Subsequent calls use this cache to make seeking to the supplied offset
4524 ** more efficient.
4525 **
4526 ** Once an overflow page-list cache has been allocated, it must be
4527 ** invalidated if some other cursor writes to the same table, or if
4528 ** the cursor is moved to a different row. Additionally, in auto-vacuum
4529 ** mode, the following events may invalidate an overflow page-list cache.
4530 **
4531 **   * An incremental vacuum,
4532 **   * A commit in auto_vacuum="full" mode,
4533 **   * Creating a table (may require moving an overflow page).
4534 */
4535 static int accessPayload(
4536   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4537   u32 offset,          /* Begin reading this far into payload */
4538   u32 amt,             /* Read this many bytes */
4539   unsigned char *pBuf, /* Write the bytes into this buffer */
4540   int eOp              /* zero to read. non-zero to write. */
4541 ){
4542   unsigned char *aPayload;
4543   int rc = SQLITE_OK;
4544   int iIdx = 0;
4545   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
4546   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
4547 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4548   unsigned char * const pBufStart = pBuf;     /* Start of original out buffer */
4549 #endif
4550 
4551   assert( pPage );
4552   assert( eOp==0 || eOp==1 );
4553   assert( pCur->eState==CURSOR_VALID );
4554   assert( pCur->ix<pPage->nCell );
4555   assert( cursorHoldsMutex(pCur) );
4556 
4557   getCellInfo(pCur);
4558   aPayload = pCur->info.pPayload;
4559   assert( offset+amt <= pCur->info.nPayload );
4560 
4561   assert( aPayload > pPage->aData );
4562   if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
4563     /* Trying to read or write past the end of the data is an error.  The
4564     ** conditional above is really:
4565     **    &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
4566     ** but is recast into its current form to avoid integer overflow problems
4567     */
4568     return SQLITE_CORRUPT_PGNO(pPage->pgno);
4569   }
4570 
4571   /* Check if data must be read/written to/from the btree page itself. */
4572   if( offset<pCur->info.nLocal ){
4573     int a = amt;
4574     if( a+offset>pCur->info.nLocal ){
4575       a = pCur->info.nLocal - offset;
4576     }
4577     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
4578     offset = 0;
4579     pBuf += a;
4580     amt -= a;
4581   }else{
4582     offset -= pCur->info.nLocal;
4583   }
4584 
4585 
4586   if( rc==SQLITE_OK && amt>0 ){
4587     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
4588     Pgno nextPage;
4589 
4590     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
4591 
4592     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
4593     **
4594     ** The aOverflow[] array is sized at one entry for each overflow page
4595     ** in the overflow chain. The page number of the first overflow page is
4596     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
4597     ** means "not yet known" (the cache is lazily populated).
4598     */
4599     if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
4600       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
4601       if( nOvfl>pCur->nOvflAlloc ){
4602         Pgno *aNew = (Pgno*)sqlite3Realloc(
4603             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
4604         );
4605         if( aNew==0 ){
4606           return SQLITE_NOMEM_BKPT;
4607         }else{
4608           pCur->nOvflAlloc = nOvfl*2;
4609           pCur->aOverflow = aNew;
4610         }
4611       }
4612       memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
4613       pCur->curFlags |= BTCF_ValidOvfl;
4614     }else{
4615       /* If the overflow page-list cache has been allocated and the
4616       ** entry for the first required overflow page is valid, skip
4617       ** directly to it.
4618       */
4619       if( pCur->aOverflow[offset/ovflSize] ){
4620         iIdx = (offset/ovflSize);
4621         nextPage = pCur->aOverflow[iIdx];
4622         offset = (offset%ovflSize);
4623       }
4624     }
4625 
4626     assert( rc==SQLITE_OK && amt>0 );
4627     while( nextPage ){
4628       /* If required, populate the overflow page-list cache. */
4629       assert( pCur->aOverflow[iIdx]==0
4630               || pCur->aOverflow[iIdx]==nextPage
4631               || CORRUPT_DB );
4632       pCur->aOverflow[iIdx] = nextPage;
4633 
4634       if( offset>=ovflSize ){
4635         /* The only reason to read this page is to obtain the page
4636         ** number for the next page in the overflow chain. The page
4637         ** data is not required. So first try to lookup the overflow
4638         ** page-list cache, if any, then fall back to the getOverflowPage()
4639         ** function.
4640         */
4641         assert( pCur->curFlags & BTCF_ValidOvfl );
4642         assert( pCur->pBtree->db==pBt->db );
4643         if( pCur->aOverflow[iIdx+1] ){
4644           nextPage = pCur->aOverflow[iIdx+1];
4645         }else{
4646           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
4647         }
4648         offset -= ovflSize;
4649       }else{
4650         /* Need to read this page properly. It contains some of the
4651         ** range of data that is being read (eOp==0) or written (eOp!=0).
4652         */
4653 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4654         sqlite3_file *fd;      /* File from which to do direct overflow read */
4655 #endif
4656         int a = amt;
4657         if( a + offset > ovflSize ){
4658           a = ovflSize - offset;
4659         }
4660 
4661 #ifdef SQLITE_DIRECT_OVERFLOW_READ
4662         /* If all the following are true:
4663         **
4664         **   1) this is a read operation, and
4665         **   2) data is required from the start of this overflow page, and
4666         **   3) there is no open write-transaction, and
4667         **   4) the database is file-backed, and
4668         **   5) the page is not in the WAL file
4669         **   6) at least 4 bytes have already been read into the output buffer
4670         **
4671         ** then data can be read directly from the database file into the
4672         ** output buffer, bypassing the page-cache altogether. This speeds
4673         ** up loading large records that span many overflow pages.
4674         */
4675         if( eOp==0                                             /* (1) */
4676          && offset==0                                          /* (2) */
4677          && pBt->inTransaction==TRANS_READ                     /* (3) */
4678          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (4) */
4679          && 0==sqlite3PagerUseWal(pBt->pPager, nextPage)       /* (5) */
4680          && &pBuf[-4]>=pBufStart                               /* (6) */
4681         ){
4682           u8 aSave[4];
4683           u8 *aWrite = &pBuf[-4];
4684           assert( aWrite>=pBufStart );                         /* due to (6) */
4685           memcpy(aSave, aWrite, 4);
4686           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
4687           nextPage = get4byte(aWrite);
4688           memcpy(aWrite, aSave, 4);
4689         }else
4690 #endif
4691 
4692         {
4693           DbPage *pDbPage;
4694           rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
4695               (eOp==0 ? PAGER_GET_READONLY : 0)
4696           );
4697           if( rc==SQLITE_OK ){
4698             aPayload = sqlite3PagerGetData(pDbPage);
4699             nextPage = get4byte(aPayload);
4700             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
4701             sqlite3PagerUnref(pDbPage);
4702             offset = 0;
4703           }
4704         }
4705         amt -= a;
4706         if( amt==0 ) return rc;
4707         pBuf += a;
4708       }
4709       if( rc ) break;
4710       iIdx++;
4711     }
4712   }
4713 
4714   if( rc==SQLITE_OK && amt>0 ){
4715     /* Overflow chain ends prematurely */
4716     return SQLITE_CORRUPT_PGNO(pPage->pgno);
4717   }
4718   return rc;
4719 }
4720 
4721 /*
4722 ** Read part of the payload for the row at which that cursor pCur is currently
4723 ** pointing.  "amt" bytes will be transferred into pBuf[].  The transfer
4724 ** begins at "offset".
4725 **
4726 ** pCur can be pointing to either a table or an index b-tree.
4727 ** If pointing to a table btree, then the content section is read.  If
4728 ** pCur is pointing to an index b-tree then the key section is read.
4729 **
4730 ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
4731 ** to a valid row in the table.  For sqlite3BtreePayloadChecked(), the
4732 ** cursor might be invalid or might need to be restored before being read.
4733 **
4734 ** Return SQLITE_OK on success or an error code if anything goes
4735 ** wrong.  An error is returned if "offset+amt" is larger than
4736 ** the available payload.
4737 */
4738 int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4739   assert( cursorHoldsMutex(pCur) );
4740   assert( pCur->eState==CURSOR_VALID );
4741   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
4742   assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
4743   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
4744 }
4745 
4746 /*
4747 ** This variant of sqlite3BtreePayload() works even if the cursor has not
4748 ** in the CURSOR_VALID state.  It is only used by the sqlite3_blob_read()
4749 ** interface.
4750 */
4751 #ifndef SQLITE_OMIT_INCRBLOB
4752 static SQLITE_NOINLINE int accessPayloadChecked(
4753   BtCursor *pCur,
4754   u32 offset,
4755   u32 amt,
4756   void *pBuf
4757 ){
4758   int rc;
4759   if ( pCur->eState==CURSOR_INVALID ){
4760     return SQLITE_ABORT;
4761   }
4762   assert( cursorOwnsBtShared(pCur) );
4763   rc = btreeRestoreCursorPosition(pCur);
4764   return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
4765 }
4766 int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
4767   if( pCur->eState==CURSOR_VALID ){
4768     assert( cursorOwnsBtShared(pCur) );
4769     return accessPayload(pCur, offset, amt, pBuf, 0);
4770   }else{
4771     return accessPayloadChecked(pCur, offset, amt, pBuf);
4772   }
4773 }
4774 #endif /* SQLITE_OMIT_INCRBLOB */
4775 
4776 /*
4777 ** Return a pointer to payload information from the entry that the
4778 ** pCur cursor is pointing to.  The pointer is to the beginning of
4779 ** the key if index btrees (pPage->intKey==0) and is the data for
4780 ** table btrees (pPage->intKey==1). The number of bytes of available
4781 ** key/data is written into *pAmt.  If *pAmt==0, then the value
4782 ** returned will not be a valid pointer.
4783 **
4784 ** This routine is an optimization.  It is common for the entire key
4785 ** and data to fit on the local page and for there to be no overflow
4786 ** pages.  When that is so, this routine can be used to access the
4787 ** key and data without making a copy.  If the key and/or data spills
4788 ** onto overflow pages, then accessPayload() must be used to reassemble
4789 ** the key/data and copy it into a preallocated buffer.
4790 **
4791 ** The pointer returned by this routine looks directly into the cached
4792 ** page of the database.  The data might change or move the next time
4793 ** any btree routine is called.
4794 */
4795 static const void *fetchPayload(
4796   BtCursor *pCur,      /* Cursor pointing to entry to read from */
4797   u32 *pAmt            /* Write the number of available bytes here */
4798 ){
4799   u32 amt;
4800   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
4801   assert( pCur->eState==CURSOR_VALID );
4802   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
4803   assert( cursorOwnsBtShared(pCur) );
4804   assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
4805   assert( pCur->info.nSize>0 );
4806   assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
4807   assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
4808   amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
4809   if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
4810   *pAmt = amt;
4811   return (void*)pCur->info.pPayload;
4812 }
4813 
4814 
4815 /*
4816 ** For the entry that cursor pCur is point to, return as
4817 ** many bytes of the key or data as are available on the local
4818 ** b-tree page.  Write the number of available bytes into *pAmt.
4819 **
4820 ** The pointer returned is ephemeral.  The key/data may move
4821 ** or be destroyed on the next call to any Btree routine,
4822 ** including calls from other threads against the same cache.
4823 ** Hence, a mutex on the BtShared should be held prior to calling
4824 ** this routine.
4825 **
4826 ** These routines is used to get quick access to key and data
4827 ** in the common case where no overflow pages are used.
4828 */
4829 const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
4830   return fetchPayload(pCur, pAmt);
4831 }
4832 
4833 
4834 /*
4835 ** Move the cursor down to a new child page.  The newPgno argument is the
4836 ** page number of the child page to move to.
4837 **
4838 ** This function returns SQLITE_CORRUPT if the page-header flags field of
4839 ** the new child page does not match the flags field of the parent (i.e.
4840 ** if an intkey page appears to be the parent of a non-intkey page, or
4841 ** vice-versa).
4842 */
4843 static int moveToChild(BtCursor *pCur, u32 newPgno){
4844   BtShared *pBt = pCur->pBt;
4845 
4846   assert( cursorOwnsBtShared(pCur) );
4847   assert( pCur->eState==CURSOR_VALID );
4848   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
4849   assert( pCur->iPage>=0 );
4850   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
4851     return SQLITE_CORRUPT_BKPT;
4852   }
4853   pCur->info.nSize = 0;
4854   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
4855   pCur->aiIdx[pCur->iPage++] = pCur->ix;
4856   pCur->ix = 0;
4857   return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
4858                         pCur, pCur->curPagerFlags);
4859 }
4860 
4861 #ifdef SQLITE_DEBUG
4862 /*
4863 ** Page pParent is an internal (non-leaf) tree page. This function
4864 ** asserts that page number iChild is the left-child if the iIdx'th
4865 ** cell in page pParent. Or, if iIdx is equal to the total number of
4866 ** cells in pParent, that page number iChild is the right-child of
4867 ** the page.
4868 */
4869 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
4870   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
4871                             ** in a corrupt database */
4872   assert( iIdx<=pParent->nCell );
4873   if( iIdx==pParent->nCell ){
4874     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
4875   }else{
4876     assert( get4byte(findCell(pParent, iIdx))==iChild );
4877   }
4878 }
4879 #else
4880 #  define assertParentIndex(x,y,z)
4881 #endif
4882 
4883 /*
4884 ** Move the cursor up to the parent page.
4885 **
4886 ** pCur->idx is set to the cell index that contains the pointer
4887 ** to the page we are coming from.  If we are coming from the
4888 ** right-most child page then pCur->idx is set to one more than
4889 ** the largest cell index.
4890 */
4891 static void moveToParent(BtCursor *pCur){
4892   assert( cursorOwnsBtShared(pCur) );
4893   assert( pCur->eState==CURSOR_VALID );
4894   assert( pCur->iPage>0 );
4895   assert( pCur->apPage[pCur->iPage] );
4896   assertParentIndex(
4897     pCur->apPage[pCur->iPage-1],
4898     pCur->aiIdx[pCur->iPage-1],
4899     pCur->apPage[pCur->iPage]->pgno
4900   );
4901   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
4902   pCur->info.nSize = 0;
4903   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
4904   pCur->ix = pCur->aiIdx[pCur->iPage-1];
4905   releasePageNotNull(pCur->apPage[pCur->iPage--]);
4906 }
4907 
4908 /*
4909 ** Move the cursor to point to the root page of its b-tree structure.
4910 **
4911 ** If the table has a virtual root page, then the cursor is moved to point
4912 ** to the virtual root page instead of the actual root page. A table has a
4913 ** virtual root page when the actual root page contains no cells and a
4914 ** single child page. This can only happen with the table rooted at page 1.
4915 **
4916 ** If the b-tree structure is empty, the cursor state is set to
4917 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
4918 ** cell located on the root (or virtual root) page and the cursor state
4919 ** is set to CURSOR_VALID.
4920 **
4921 ** If this function returns successfully, it may be assumed that the
4922 ** page-header flags indicate that the [virtual] root-page is the expected
4923 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
4924 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
4925 ** indicating a table b-tree, or if the caller did specify a KeyInfo
4926 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
4927 ** b-tree).
4928 */
4929 static int moveToRoot(BtCursor *pCur){
4930   MemPage *pRoot;
4931   int rc = SQLITE_OK;
4932 
4933   assert( cursorOwnsBtShared(pCur) );
4934   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
4935   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
4936   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
4937   assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
4938 
4939   if( pCur->iPage>=0 ){
4940     if( pCur->iPage ){
4941       do{
4942         assert( pCur->apPage[pCur->iPage]!=0 );
4943         releasePageNotNull(pCur->apPage[pCur->iPage--]);
4944       }while( pCur->iPage);
4945       goto skip_init;
4946     }
4947   }else if( pCur->pgnoRoot==0 ){
4948     pCur->eState = CURSOR_INVALID;
4949     return SQLITE_OK;
4950   }else{
4951     assert( pCur->iPage==(-1) );
4952     if( pCur->eState>=CURSOR_REQUIRESEEK ){
4953       if( pCur->eState==CURSOR_FAULT ){
4954         assert( pCur->skipNext!=SQLITE_OK );
4955         return pCur->skipNext;
4956       }
4957       sqlite3BtreeClearCursor(pCur);
4958     }
4959     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
4960                         0, pCur->curPagerFlags);
4961     if( rc!=SQLITE_OK ){
4962       pCur->eState = CURSOR_INVALID;
4963        return rc;
4964     }
4965     pCur->iPage = 0;
4966     pCur->curIntKey = pCur->apPage[0]->intKey;
4967   }
4968   pRoot = pCur->apPage[0];
4969   assert( pRoot->pgno==pCur->pgnoRoot );
4970 
4971   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
4972   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
4973   ** NULL, the caller expects a table b-tree. If this is not the case,
4974   ** return an SQLITE_CORRUPT error.
4975   **
4976   ** Earlier versions of SQLite assumed that this test could not fail
4977   ** if the root page was already loaded when this function was called (i.e.
4978   ** if pCur->iPage>=0). But this is not so if the database is corrupted
4979   ** in such a way that page pRoot is linked into a second b-tree table
4980   ** (or the freelist).  */
4981   assert( pRoot->intKey==1 || pRoot->intKey==0 );
4982   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
4983     return SQLITE_CORRUPT_PGNO(pCur->apPage[pCur->iPage]->pgno);
4984   }
4985 
4986 skip_init:
4987   pCur->ix = 0;
4988   pCur->info.nSize = 0;
4989   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
4990 
4991   pRoot = pCur->apPage[0];
4992   if( pRoot->nCell>0 ){
4993     pCur->eState = CURSOR_VALID;
4994   }else if( !pRoot->leaf ){
4995     Pgno subpage;
4996     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
4997     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
4998     pCur->eState = CURSOR_VALID;
4999     rc = moveToChild(pCur, subpage);
5000   }else{
5001     pCur->eState = CURSOR_INVALID;
5002   }
5003   return rc;
5004 }
5005 
5006 /*
5007 ** Move the cursor down to the left-most leaf entry beneath the
5008 ** entry to which it is currently pointing.
5009 **
5010 ** The left-most leaf is the one with the smallest key - the first
5011 ** in ascending order.
5012 */
5013 static int moveToLeftmost(BtCursor *pCur){
5014   Pgno pgno;
5015   int rc = SQLITE_OK;
5016   MemPage *pPage;
5017 
5018   assert( cursorOwnsBtShared(pCur) );
5019   assert( pCur->eState==CURSOR_VALID );
5020   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
5021     assert( pCur->ix<pPage->nCell );
5022     pgno = get4byte(findCell(pPage, pCur->ix));
5023     rc = moveToChild(pCur, pgno);
5024   }
5025   return rc;
5026 }
5027 
5028 /*
5029 ** Move the cursor down to the right-most leaf entry beneath the
5030 ** page to which it is currently pointing.  Notice the difference
5031 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
5032 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5033 ** finds the right-most entry beneath the *page*.
5034 **
5035 ** The right-most entry is the one with the largest key - the last
5036 ** key in ascending order.
5037 */
5038 static int moveToRightmost(BtCursor *pCur){
5039   Pgno pgno;
5040   int rc = SQLITE_OK;
5041   MemPage *pPage = 0;
5042 
5043   assert( cursorOwnsBtShared(pCur) );
5044   assert( pCur->eState==CURSOR_VALID );
5045   while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
5046     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5047     pCur->ix = pPage->nCell;
5048     rc = moveToChild(pCur, pgno);
5049     if( rc ) return rc;
5050   }
5051   pCur->ix = pPage->nCell-1;
5052   assert( pCur->info.nSize==0 );
5053   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5054   return SQLITE_OK;
5055 }
5056 
5057 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
5058 ** on success.  Set *pRes to 0 if the cursor actually points to something
5059 ** or set *pRes to 1 if the table is empty.
5060 */
5061 int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5062   int rc;
5063 
5064   assert( cursorOwnsBtShared(pCur) );
5065   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5066   rc = moveToRoot(pCur);
5067   if( rc==SQLITE_OK ){
5068     if( pCur->eState==CURSOR_INVALID ){
5069       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
5070       *pRes = 1;
5071     }else{
5072       assert( pCur->apPage[pCur->iPage]->nCell>0 );
5073       *pRes = 0;
5074       rc = moveToLeftmost(pCur);
5075     }
5076   }
5077   return rc;
5078 }
5079 
5080 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
5081 ** on success.  Set *pRes to 0 if the cursor actually points to something
5082 ** or set *pRes to 1 if the table is empty.
5083 */
5084 int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5085   int rc;
5086 
5087   assert( cursorOwnsBtShared(pCur) );
5088   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5089 
5090   /* If the cursor already points to the last entry, this is a no-op. */
5091   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5092 #ifdef SQLITE_DEBUG
5093     /* This block serves to assert() that the cursor really does point
5094     ** to the last entry in the b-tree. */
5095     int ii;
5096     for(ii=0; ii<pCur->iPage; ii++){
5097       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
5098     }
5099     assert( pCur->ix==pCur->apPage[pCur->iPage]->nCell-1 );
5100     assert( pCur->apPage[pCur->iPage]->leaf );
5101 #endif
5102     return SQLITE_OK;
5103   }
5104 
5105   rc = moveToRoot(pCur);
5106   if( rc==SQLITE_OK ){
5107     if( CURSOR_INVALID==pCur->eState ){
5108       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
5109       *pRes = 1;
5110     }else{
5111       assert( pCur->eState==CURSOR_VALID );
5112       *pRes = 0;
5113       rc = moveToRightmost(pCur);
5114       if( rc==SQLITE_OK ){
5115         pCur->curFlags |= BTCF_AtLast;
5116       }else{
5117         pCur->curFlags &= ~BTCF_AtLast;
5118       }
5119 
5120     }
5121   }
5122   return rc;
5123 }
5124 
5125 /* Move the cursor so that it points to an entry near the key
5126 ** specified by pIdxKey or intKey.   Return a success code.
5127 **
5128 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
5129 ** must be NULL.  For index tables, pIdxKey is used and intKey
5130 ** is ignored.
5131 **
5132 ** If an exact match is not found, then the cursor is always
5133 ** left pointing at a leaf page which would hold the entry if it
5134 ** were present.  The cursor might point to an entry that comes
5135 ** before or after the key.
5136 **
5137 ** An integer is written into *pRes which is the result of
5138 ** comparing the key with the entry to which the cursor is
5139 ** pointing.  The meaning of the integer written into
5140 ** *pRes is as follows:
5141 **
5142 **     *pRes<0      The cursor is left pointing at an entry that
5143 **                  is smaller than intKey/pIdxKey or if the table is empty
5144 **                  and the cursor is therefore left point to nothing.
5145 **
5146 **     *pRes==0     The cursor is left pointing at an entry that
5147 **                  exactly matches intKey/pIdxKey.
5148 **
5149 **     *pRes>0      The cursor is left pointing at an entry that
5150 **                  is larger than intKey/pIdxKey.
5151 **
5152 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
5153 ** exists an entry in the table that exactly matches pIdxKey.
5154 */
5155 int sqlite3BtreeMovetoUnpacked(
5156   BtCursor *pCur,          /* The cursor to be moved */
5157   UnpackedRecord *pIdxKey, /* Unpacked index key */
5158   i64 intKey,              /* The table key */
5159   int biasRight,           /* If true, bias the search to the high end */
5160   int *pRes                /* Write search results here */
5161 ){
5162   int rc;
5163   RecordCompare xRecordCompare;
5164 
5165   assert( cursorOwnsBtShared(pCur) );
5166   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5167   assert( pRes );
5168   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
5169   assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
5170 
5171   /* If the cursor is already positioned at the point we are trying
5172   ** to move to, then just return without doing any work */
5173   if( pIdxKey==0
5174    && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
5175   ){
5176     if( pCur->info.nKey==intKey ){
5177       *pRes = 0;
5178       return SQLITE_OK;
5179     }
5180     if( pCur->info.nKey<intKey ){
5181       if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5182         *pRes = -1;
5183         return SQLITE_OK;
5184       }
5185       /* If the requested key is one more than the previous key, then
5186       ** try to get there using sqlite3BtreeNext() rather than a full
5187       ** binary search.  This is an optimization only.  The correct answer
5188       ** is still obtained without this case, only a little more slowely */
5189       if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
5190         *pRes = 0;
5191         rc = sqlite3BtreeNext(pCur, 0);
5192         if( rc==SQLITE_OK ){
5193           getCellInfo(pCur);
5194           if( pCur->info.nKey==intKey ){
5195             return SQLITE_OK;
5196           }
5197         }else if( rc==SQLITE_DONE ){
5198           rc = SQLITE_OK;
5199         }else{
5200           return rc;
5201         }
5202       }
5203     }
5204   }
5205 
5206   if( pIdxKey ){
5207     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
5208     pIdxKey->errCode = 0;
5209     assert( pIdxKey->default_rc==1
5210          || pIdxKey->default_rc==0
5211          || pIdxKey->default_rc==-1
5212     );
5213   }else{
5214     xRecordCompare = 0; /* All keys are integers */
5215   }
5216 
5217   rc = moveToRoot(pCur);
5218   if( rc ){
5219     return rc;
5220   }
5221   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
5222   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
5223   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
5224   if( pCur->eState==CURSOR_INVALID ){
5225     *pRes = -1;
5226     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
5227     return SQLITE_OK;
5228   }
5229   assert( pCur->apPage[0]->intKey==pCur->curIntKey );
5230   assert( pCur->curIntKey || pIdxKey );
5231   for(;;){
5232     int lwr, upr, idx, c;
5233     Pgno chldPg;
5234     MemPage *pPage = pCur->apPage[pCur->iPage];
5235     u8 *pCell;                          /* Pointer to current cell in pPage */
5236 
5237     /* pPage->nCell must be greater than zero. If this is the root-page
5238     ** the cursor would have been INVALID above and this for(;;) loop
5239     ** not run. If this is not the root-page, then the moveToChild() routine
5240     ** would have already detected db corruption. Similarly, pPage must
5241     ** be the right kind (index or table) of b-tree page. Otherwise
5242     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
5243     assert( pPage->nCell>0 );
5244     assert( pPage->intKey==(pIdxKey==0) );
5245     lwr = 0;
5246     upr = pPage->nCell-1;
5247     assert( biasRight==0 || biasRight==1 );
5248     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5249     pCur->ix = (u16)idx;
5250     if( xRecordCompare==0 ){
5251       for(;;){
5252         i64 nCellKey;
5253         pCell = findCellPastPtr(pPage, idx);
5254         if( pPage->intKeyLeaf ){
5255           while( 0x80 <= *(pCell++) ){
5256             if( pCell>=pPage->aDataEnd ){
5257               return SQLITE_CORRUPT_PGNO(pPage->pgno);
5258             }
5259           }
5260         }
5261         getVarint(pCell, (u64*)&nCellKey);
5262         if( nCellKey<intKey ){
5263           lwr = idx+1;
5264           if( lwr>upr ){ c = -1; break; }
5265         }else if( nCellKey>intKey ){
5266           upr = idx-1;
5267           if( lwr>upr ){ c = +1; break; }
5268         }else{
5269           assert( nCellKey==intKey );
5270           pCur->ix = (u16)idx;
5271           if( !pPage->leaf ){
5272             lwr = idx;
5273             goto moveto_next_layer;
5274           }else{
5275             pCur->curFlags |= BTCF_ValidNKey;
5276             pCur->info.nKey = nCellKey;
5277             pCur->info.nSize = 0;
5278             *pRes = 0;
5279             return SQLITE_OK;
5280           }
5281         }
5282         assert( lwr+upr>=0 );
5283         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
5284       }
5285     }else{
5286       for(;;){
5287         int nCell;  /* Size of the pCell cell in bytes */
5288         pCell = findCellPastPtr(pPage, idx);
5289 
5290         /* The maximum supported page-size is 65536 bytes. This means that
5291         ** the maximum number of record bytes stored on an index B-Tree
5292         ** page is less than 16384 bytes and may be stored as a 2-byte
5293         ** varint. This information is used to attempt to avoid parsing
5294         ** the entire cell by checking for the cases where the record is
5295         ** stored entirely within the b-tree page by inspecting the first
5296         ** 2 bytes of the cell.
5297         */
5298         nCell = pCell[0];
5299         if( nCell<=pPage->max1bytePayload ){
5300           /* This branch runs if the record-size field of the cell is a
5301           ** single byte varint and the record fits entirely on the main
5302           ** b-tree page.  */
5303           testcase( pCell+nCell+1==pPage->aDataEnd );
5304           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
5305         }else if( !(pCell[1] & 0x80)
5306           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
5307         ){
5308           /* The record-size field is a 2 byte varint and the record
5309           ** fits entirely on the main b-tree page.  */
5310           testcase( pCell+nCell+2==pPage->aDataEnd );
5311           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
5312         }else{
5313           /* The record flows over onto one or more overflow pages. In
5314           ** this case the whole cell needs to be parsed, a buffer allocated
5315           ** and accessPayload() used to retrieve the record into the
5316           ** buffer before VdbeRecordCompare() can be called.
5317           **
5318           ** If the record is corrupt, the xRecordCompare routine may read
5319           ** up to two varints past the end of the buffer. An extra 18
5320           ** bytes of padding is allocated at the end of the buffer in
5321           ** case this happens.  */
5322           void *pCellKey;
5323           u8 * const pCellBody = pCell - pPage->childPtrSize;
5324           pPage->xParseCell(pPage, pCellBody, &pCur->info);
5325           nCell = (int)pCur->info.nKey;
5326           testcase( nCell<0 );   /* True if key size is 2^32 or more */
5327           testcase( nCell==0 );  /* Invalid key size:  0x80 0x80 0x00 */
5328           testcase( nCell==1 );  /* Invalid key size:  0x80 0x80 0x01 */
5329           testcase( nCell==2 );  /* Minimum legal index key size */
5330           if( nCell<2 ){
5331             rc = SQLITE_CORRUPT_PGNO(pPage->pgno);
5332             goto moveto_finish;
5333           }
5334           pCellKey = sqlite3Malloc( nCell+18 );
5335           if( pCellKey==0 ){
5336             rc = SQLITE_NOMEM_BKPT;
5337             goto moveto_finish;
5338           }
5339           pCur->ix = (u16)idx;
5340           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
5341           pCur->curFlags &= ~BTCF_ValidOvfl;
5342           if( rc ){
5343             sqlite3_free(pCellKey);
5344             goto moveto_finish;
5345           }
5346           c = xRecordCompare(nCell, pCellKey, pIdxKey);
5347           sqlite3_free(pCellKey);
5348         }
5349         assert(
5350             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
5351          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
5352         );
5353         if( c<0 ){
5354           lwr = idx+1;
5355         }else if( c>0 ){
5356           upr = idx-1;
5357         }else{
5358           assert( c==0 );
5359           *pRes = 0;
5360           rc = SQLITE_OK;
5361           pCur->ix = (u16)idx;
5362           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
5363           goto moveto_finish;
5364         }
5365         if( lwr>upr ) break;
5366         assert( lwr+upr>=0 );
5367         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
5368       }
5369     }
5370     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
5371     assert( pPage->isInit );
5372     if( pPage->leaf ){
5373       assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
5374       pCur->ix = (u16)idx;
5375       *pRes = c;
5376       rc = SQLITE_OK;
5377       goto moveto_finish;
5378     }
5379 moveto_next_layer:
5380     if( lwr>=pPage->nCell ){
5381       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5382     }else{
5383       chldPg = get4byte(findCell(pPage, lwr));
5384     }
5385     pCur->ix = (u16)lwr;
5386     rc = moveToChild(pCur, chldPg);
5387     if( rc ) break;
5388   }
5389 moveto_finish:
5390   pCur->info.nSize = 0;
5391   assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5392   return rc;
5393 }
5394 
5395 
5396 /*
5397 ** Return TRUE if the cursor is not pointing at an entry of the table.
5398 **
5399 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
5400 ** past the last entry in the table or sqlite3BtreePrev() moves past
5401 ** the first entry.  TRUE is also returned if the table is empty.
5402 */
5403 int sqlite3BtreeEof(BtCursor *pCur){
5404   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
5405   ** have been deleted? This API will need to change to return an error code
5406   ** as well as the boolean result value.
5407   */
5408   return (CURSOR_VALID!=pCur->eState);
5409 }
5410 
5411 /*
5412 ** Return an estimate for the number of rows in the table that pCur is
5413 ** pointing to.  Return a negative number if no estimate is currently
5414 ** available.
5415 */
5416 i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
5417   i64 n;
5418   u8 i;
5419 
5420   assert( cursorOwnsBtShared(pCur) );
5421   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5422 
5423   /* Currently this interface is only called by the OP_IfSmaller
5424   ** opcode, and it that case the cursor will always be valid and
5425   ** will always point to a leaf node. */
5426   if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
5427   if( NEVER(pCur->apPage[pCur->iPage]->leaf==0) ) return -1;
5428 
5429   for(n=1, i=0; i<=pCur->iPage; i++){
5430     n *= pCur->apPage[i]->nCell;
5431   }
5432   return n;
5433 }
5434 
5435 /*
5436 ** Advance the cursor to the next entry in the database.
5437 ** Return value:
5438 **
5439 **    SQLITE_OK        success
5440 **    SQLITE_DONE      cursor is already pointing at the last element
5441 **    otherwise        some kind of error occurred
5442 **
5443 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
5444 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
5445 ** to the next cell on the current page.  The (slower) btreeNext() helper
5446 ** routine is called when it is necessary to move to a different page or
5447 ** to restore the cursor.
5448 **
5449 ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
5450 ** cursor corresponds to an SQL index and this routine could have been
5451 ** skipped if the SQL index had been a unique index.  The F argument
5452 ** is a hint to the implement.  SQLite btree implementation does not use
5453 ** this hint, but COMDB2 does.
5454 */
5455 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
5456   int rc;
5457   int idx;
5458   MemPage *pPage;
5459 
5460   assert( cursorOwnsBtShared(pCur) );
5461   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5462   if( pCur->eState!=CURSOR_VALID ){
5463     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5464     rc = restoreCursorPosition(pCur);
5465     if( rc!=SQLITE_OK ){
5466       return rc;
5467     }
5468     if( CURSOR_INVALID==pCur->eState ){
5469       return SQLITE_DONE;
5470     }
5471     if( pCur->skipNext ){
5472       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5473       pCur->eState = CURSOR_VALID;
5474       if( pCur->skipNext>0 ){
5475         pCur->skipNext = 0;
5476         return SQLITE_OK;
5477       }
5478       pCur->skipNext = 0;
5479     }
5480   }
5481 
5482   pPage = pCur->apPage[pCur->iPage];
5483   idx = ++pCur->ix;
5484   assert( pPage->isInit );
5485 
5486   /* If the database file is corrupt, it is possible for the value of idx
5487   ** to be invalid here. This can only occur if a second cursor modifies
5488   ** the page while cursor pCur is holding a reference to it. Which can
5489   ** only happen if the database is corrupt in such a way as to link the
5490   ** page into more than one b-tree structure. */
5491   testcase( idx>pPage->nCell );
5492 
5493   if( idx>=pPage->nCell ){
5494     if( !pPage->leaf ){
5495       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
5496       if( rc ) return rc;
5497       return moveToLeftmost(pCur);
5498     }
5499     do{
5500       if( pCur->iPage==0 ){
5501         pCur->eState = CURSOR_INVALID;
5502         return SQLITE_DONE;
5503       }
5504       moveToParent(pCur);
5505       pPage = pCur->apPage[pCur->iPage];
5506     }while( pCur->ix>=pPage->nCell );
5507     if( pPage->intKey ){
5508       return sqlite3BtreeNext(pCur, 0);
5509     }else{
5510       return SQLITE_OK;
5511     }
5512   }
5513   if( pPage->leaf ){
5514     return SQLITE_OK;
5515   }else{
5516     return moveToLeftmost(pCur);
5517   }
5518 }
5519 int sqlite3BtreeNext(BtCursor *pCur, int flags){
5520   MemPage *pPage;
5521   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5522   assert( cursorOwnsBtShared(pCur) );
5523   assert( flags==0 || flags==1 );
5524   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5525   pCur->info.nSize = 0;
5526   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5527   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
5528   pPage = pCur->apPage[pCur->iPage];
5529   if( (++pCur->ix)>=pPage->nCell ){
5530     pCur->ix--;
5531     return btreeNext(pCur);
5532   }
5533   if( pPage->leaf ){
5534     return SQLITE_OK;
5535   }else{
5536     return moveToLeftmost(pCur);
5537   }
5538 }
5539 
5540 /*
5541 ** Step the cursor to the back to the previous entry in the database.
5542 ** Return values:
5543 **
5544 **     SQLITE_OK     success
5545 **     SQLITE_DONE   the cursor is already on the first element of the table
5546 **     otherwise     some kind of error occurred
5547 **
5548 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
5549 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
5550 ** to the previous cell on the current page.  The (slower) btreePrevious()
5551 ** helper routine is called when it is necessary to move to a different page
5552 ** or to restore the cursor.
5553 **
5554 ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
5555 ** the cursor corresponds to an SQL index and this routine could have been
5556 ** skipped if the SQL index had been a unique index.  The F argument is a
5557 ** hint to the implement.  The native SQLite btree implementation does not
5558 ** use this hint, but COMDB2 does.
5559 */
5560 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
5561   int rc;
5562   MemPage *pPage;
5563 
5564   assert( cursorOwnsBtShared(pCur) );
5565   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5566   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
5567   assert( pCur->info.nSize==0 );
5568   if( pCur->eState!=CURSOR_VALID ){
5569     rc = restoreCursorPosition(pCur);
5570     if( rc!=SQLITE_OK ){
5571       return rc;
5572     }
5573     if( CURSOR_INVALID==pCur->eState ){
5574       return SQLITE_DONE;
5575     }
5576     if( pCur->skipNext ){
5577       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
5578       pCur->eState = CURSOR_VALID;
5579       if( pCur->skipNext<0 ){
5580         pCur->skipNext = 0;
5581         return SQLITE_OK;
5582       }
5583       pCur->skipNext = 0;
5584     }
5585   }
5586 
5587   pPage = pCur->apPage[pCur->iPage];
5588   assert( pPage->isInit );
5589   if( !pPage->leaf ){
5590     int idx = pCur->ix;
5591     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
5592     if( rc ) return rc;
5593     rc = moveToRightmost(pCur);
5594   }else{
5595     while( pCur->ix==0 ){
5596       if( pCur->iPage==0 ){
5597         pCur->eState = CURSOR_INVALID;
5598         return SQLITE_DONE;
5599       }
5600       moveToParent(pCur);
5601     }
5602     assert( pCur->info.nSize==0 );
5603     assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
5604 
5605     pCur->ix--;
5606     pPage = pCur->apPage[pCur->iPage];
5607     if( pPage->intKey && !pPage->leaf ){
5608       rc = sqlite3BtreePrevious(pCur, 0);
5609     }else{
5610       rc = SQLITE_OK;
5611     }
5612   }
5613   return rc;
5614 }
5615 int sqlite3BtreePrevious(BtCursor *pCur, int flags){
5616   assert( cursorOwnsBtShared(pCur) );
5617   assert( flags==0 || flags==1 );
5618   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
5619   UNUSED_PARAMETER( flags );  /* Used in COMDB2 but not native SQLite */
5620   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
5621   pCur->info.nSize = 0;
5622   if( pCur->eState!=CURSOR_VALID
5623    || pCur->ix==0
5624    || pCur->apPage[pCur->iPage]->leaf==0
5625   ){
5626     return btreePrevious(pCur);
5627   }
5628   pCur->ix--;
5629   return SQLITE_OK;
5630 }
5631 
5632 /*
5633 ** Allocate a new page from the database file.
5634 **
5635 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
5636 ** has already been called on the new page.)  The new page has also
5637 ** been referenced and the calling routine is responsible for calling
5638 ** sqlite3PagerUnref() on the new page when it is done.
5639 **
5640 ** SQLITE_OK is returned on success.  Any other return value indicates
5641 ** an error.  *ppPage is set to NULL in the event of an error.
5642 **
5643 ** If the "nearby" parameter is not 0, then an effort is made to
5644 ** locate a page close to the page number "nearby".  This can be used in an
5645 ** attempt to keep related pages close to each other in the database file,
5646 ** which in turn can make database access faster.
5647 **
5648 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
5649 ** anywhere on the free-list, then it is guaranteed to be returned.  If
5650 ** eMode is BTALLOC_LT then the page returned will be less than or equal
5651 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
5652 ** are no restrictions on which page is returned.
5653 */
5654 static int allocateBtreePage(
5655   BtShared *pBt,         /* The btree */
5656   MemPage **ppPage,      /* Store pointer to the allocated page here */
5657   Pgno *pPgno,           /* Store the page number here */
5658   Pgno nearby,           /* Search for a page near this one */
5659   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
5660 ){
5661   MemPage *pPage1;
5662   int rc;
5663   u32 n;     /* Number of pages on the freelist */
5664   u32 k;     /* Number of leaves on the trunk of the freelist */
5665   MemPage *pTrunk = 0;
5666   MemPage *pPrevTrunk = 0;
5667   Pgno mxPage;     /* Total size of the database file */
5668 
5669   assert( sqlite3_mutex_held(pBt->mutex) );
5670   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
5671   pPage1 = pBt->pPage1;
5672   mxPage = btreePagecount(pBt);
5673   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
5674   ** stores stores the total number of pages on the freelist. */
5675   n = get4byte(&pPage1->aData[36]);
5676   testcase( n==mxPage-1 );
5677   if( n>=mxPage ){
5678     return SQLITE_CORRUPT_BKPT;
5679   }
5680   if( n>0 ){
5681     /* There are pages on the freelist.  Reuse one of those pages. */
5682     Pgno iTrunk;
5683     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
5684     u32 nSearch = 0;   /* Count of the number of search attempts */
5685 
5686     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
5687     ** shows that the page 'nearby' is somewhere on the free-list, then
5688     ** the entire-list will be searched for that page.
5689     */
5690 #ifndef SQLITE_OMIT_AUTOVACUUM
5691     if( eMode==BTALLOC_EXACT ){
5692       if( nearby<=mxPage ){
5693         u8 eType;
5694         assert( nearby>0 );
5695         assert( pBt->autoVacuum );
5696         rc = ptrmapGet(pBt, nearby, &eType, 0);
5697         if( rc ) return rc;
5698         if( eType==PTRMAP_FREEPAGE ){
5699           searchList = 1;
5700         }
5701       }
5702     }else if( eMode==BTALLOC_LE ){
5703       searchList = 1;
5704     }
5705 #endif
5706 
5707     /* Decrement the free-list count by 1. Set iTrunk to the index of the
5708     ** first free-list trunk page. iPrevTrunk is initially 1.
5709     */
5710     rc = sqlite3PagerWrite(pPage1->pDbPage);
5711     if( rc ) return rc;
5712     put4byte(&pPage1->aData[36], n-1);
5713 
5714     /* The code within this loop is run only once if the 'searchList' variable
5715     ** is not true. Otherwise, it runs once for each trunk-page on the
5716     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
5717     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
5718     */
5719     do {
5720       pPrevTrunk = pTrunk;
5721       if( pPrevTrunk ){
5722         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
5723         ** is the page number of the next freelist trunk page in the list or
5724         ** zero if this is the last freelist trunk page. */
5725         iTrunk = get4byte(&pPrevTrunk->aData[0]);
5726       }else{
5727         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
5728         ** stores the page number of the first page of the freelist, or zero if
5729         ** the freelist is empty. */
5730         iTrunk = get4byte(&pPage1->aData[32]);
5731       }
5732       testcase( iTrunk==mxPage );
5733       if( iTrunk>mxPage || nSearch++ > n ){
5734         rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
5735       }else{
5736         rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
5737       }
5738       if( rc ){
5739         pTrunk = 0;
5740         goto end_allocate_page;
5741       }
5742       assert( pTrunk!=0 );
5743       assert( pTrunk->aData!=0 );
5744       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
5745       ** is the number of leaf page pointers to follow. */
5746       k = get4byte(&pTrunk->aData[4]);
5747       if( k==0 && !searchList ){
5748         /* The trunk has no leaves and the list is not being searched.
5749         ** So extract the trunk page itself and use it as the newly
5750         ** allocated page */
5751         assert( pPrevTrunk==0 );
5752         rc = sqlite3PagerWrite(pTrunk->pDbPage);
5753         if( rc ){
5754           goto end_allocate_page;
5755         }
5756         *pPgno = iTrunk;
5757         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5758         *ppPage = pTrunk;
5759         pTrunk = 0;
5760         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5761       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
5762         /* Value of k is out of range.  Database corruption */
5763         rc = SQLITE_CORRUPT_PGNO(iTrunk);
5764         goto end_allocate_page;
5765 #ifndef SQLITE_OMIT_AUTOVACUUM
5766       }else if( searchList
5767             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
5768       ){
5769         /* The list is being searched and this trunk page is the page
5770         ** to allocate, regardless of whether it has leaves.
5771         */
5772         *pPgno = iTrunk;
5773         *ppPage = pTrunk;
5774         searchList = 0;
5775         rc = sqlite3PagerWrite(pTrunk->pDbPage);
5776         if( rc ){
5777           goto end_allocate_page;
5778         }
5779         if( k==0 ){
5780           if( !pPrevTrunk ){
5781             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
5782           }else{
5783             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5784             if( rc!=SQLITE_OK ){
5785               goto end_allocate_page;
5786             }
5787             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
5788           }
5789         }else{
5790           /* The trunk page is required by the caller but it contains
5791           ** pointers to free-list leaves. The first leaf becomes a trunk
5792           ** page in this case.
5793           */
5794           MemPage *pNewTrunk;
5795           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
5796           if( iNewTrunk>mxPage ){
5797             rc = SQLITE_CORRUPT_PGNO(iTrunk);
5798             goto end_allocate_page;
5799           }
5800           testcase( iNewTrunk==mxPage );
5801           rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
5802           if( rc!=SQLITE_OK ){
5803             goto end_allocate_page;
5804           }
5805           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
5806           if( rc!=SQLITE_OK ){
5807             releasePage(pNewTrunk);
5808             goto end_allocate_page;
5809           }
5810           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
5811           put4byte(&pNewTrunk->aData[4], k-1);
5812           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
5813           releasePage(pNewTrunk);
5814           if( !pPrevTrunk ){
5815             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
5816             put4byte(&pPage1->aData[32], iNewTrunk);
5817           }else{
5818             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
5819             if( rc ){
5820               goto end_allocate_page;
5821             }
5822             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
5823           }
5824         }
5825         pTrunk = 0;
5826         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
5827 #endif
5828       }else if( k>0 ){
5829         /* Extract a leaf from the trunk */
5830         u32 closest;
5831         Pgno iPage;
5832         unsigned char *aData = pTrunk->aData;
5833         if( nearby>0 ){
5834           u32 i;
5835           closest = 0;
5836           if( eMode==BTALLOC_LE ){
5837             for(i=0; i<k; i++){
5838               iPage = get4byte(&aData[8+i*4]);
5839               if( iPage<=nearby ){
5840                 closest = i;
5841                 break;
5842               }
5843             }
5844           }else{
5845             int dist;
5846             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
5847             for(i=1; i<k; i++){
5848               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
5849               if( d2<dist ){
5850                 closest = i;
5851                 dist = d2;
5852               }
5853             }
5854           }
5855         }else{
5856           closest = 0;
5857         }
5858 
5859         iPage = get4byte(&aData[8+closest*4]);
5860         testcase( iPage==mxPage );
5861         if( iPage>mxPage ){
5862           rc = SQLITE_CORRUPT_PGNO(iTrunk);
5863           goto end_allocate_page;
5864         }
5865         testcase( iPage==mxPage );
5866         if( !searchList
5867          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
5868         ){
5869           int noContent;
5870           *pPgno = iPage;
5871           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
5872                  ": %d more free pages\n",
5873                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
5874           rc = sqlite3PagerWrite(pTrunk->pDbPage);
5875           if( rc ) goto end_allocate_page;
5876           if( closest<k-1 ){
5877             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
5878           }
5879           put4byte(&aData[4], k-1);
5880           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
5881           rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
5882           if( rc==SQLITE_OK ){
5883             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
5884             if( rc!=SQLITE_OK ){
5885               releasePage(*ppPage);
5886               *ppPage = 0;
5887             }
5888           }
5889           searchList = 0;
5890         }
5891       }
5892       releasePage(pPrevTrunk);
5893       pPrevTrunk = 0;
5894     }while( searchList );
5895   }else{
5896     /* There are no pages on the freelist, so append a new page to the
5897     ** database image.
5898     **
5899     ** Normally, new pages allocated by this block can be requested from the
5900     ** pager layer with the 'no-content' flag set. This prevents the pager
5901     ** from trying to read the pages content from disk. However, if the
5902     ** current transaction has already run one or more incremental-vacuum
5903     ** steps, then the page we are about to allocate may contain content
5904     ** that is required in the event of a rollback. In this case, do
5905     ** not set the no-content flag. This causes the pager to load and journal
5906     ** the current page content before overwriting it.
5907     **
5908     ** Note that the pager will not actually attempt to load or journal
5909     ** content for any page that really does lie past the end of the database
5910     ** file on disk. So the effects of disabling the no-content optimization
5911     ** here are confined to those pages that lie between the end of the
5912     ** database image and the end of the database file.
5913     */
5914     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
5915 
5916     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
5917     if( rc ) return rc;
5918     pBt->nPage++;
5919     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
5920 
5921 #ifndef SQLITE_OMIT_AUTOVACUUM
5922     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
5923       /* If *pPgno refers to a pointer-map page, allocate two new pages
5924       ** at the end of the file instead of one. The first allocated page
5925       ** becomes a new pointer-map page, the second is used by the caller.
5926       */
5927       MemPage *pPg = 0;
5928       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
5929       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
5930       rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
5931       if( rc==SQLITE_OK ){
5932         rc = sqlite3PagerWrite(pPg->pDbPage);
5933         releasePage(pPg);
5934       }
5935       if( rc ) return rc;
5936       pBt->nPage++;
5937       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
5938     }
5939 #endif
5940     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
5941     *pPgno = pBt->nPage;
5942 
5943     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
5944     rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
5945     if( rc ) return rc;
5946     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
5947     if( rc!=SQLITE_OK ){
5948       releasePage(*ppPage);
5949       *ppPage = 0;
5950     }
5951     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
5952   }
5953 
5954   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
5955 
5956 end_allocate_page:
5957   releasePage(pTrunk);
5958   releasePage(pPrevTrunk);
5959   assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
5960   assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
5961   return rc;
5962 }
5963 
5964 /*
5965 ** This function is used to add page iPage to the database file free-list.
5966 ** It is assumed that the page is not already a part of the free-list.
5967 **
5968 ** The value passed as the second argument to this function is optional.
5969 ** If the caller happens to have a pointer to the MemPage object
5970 ** corresponding to page iPage handy, it may pass it as the second value.
5971 ** Otherwise, it may pass NULL.
5972 **
5973 ** If a pointer to a MemPage object is passed as the second argument,
5974 ** its reference count is not altered by this function.
5975 */
5976 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
5977   MemPage *pTrunk = 0;                /* Free-list trunk page */
5978   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
5979   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
5980   MemPage *pPage;                     /* Page being freed. May be NULL. */
5981   int rc;                             /* Return Code */
5982   int nFree;                          /* Initial number of pages on free-list */
5983 
5984   assert( sqlite3_mutex_held(pBt->mutex) );
5985   assert( CORRUPT_DB || iPage>1 );
5986   assert( !pMemPage || pMemPage->pgno==iPage );
5987 
5988   if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
5989   if( pMemPage ){
5990     pPage = pMemPage;
5991     sqlite3PagerRef(pPage->pDbPage);
5992   }else{
5993     pPage = btreePageLookup(pBt, iPage);
5994   }
5995 
5996   /* Increment the free page count on pPage1 */
5997   rc = sqlite3PagerWrite(pPage1->pDbPage);
5998   if( rc ) goto freepage_out;
5999   nFree = get4byte(&pPage1->aData[36]);
6000   put4byte(&pPage1->aData[36], nFree+1);
6001 
6002   if( pBt->btsFlags & BTS_SECURE_DELETE ){
6003     /* If the secure_delete option is enabled, then
6004     ** always fully overwrite deleted information with zeros.
6005     */
6006     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6007      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6008     ){
6009       goto freepage_out;
6010     }
6011     memset(pPage->aData, 0, pPage->pBt->pageSize);
6012   }
6013 
6014   /* If the database supports auto-vacuum, write an entry in the pointer-map
6015   ** to indicate that the page is free.
6016   */
6017   if( ISAUTOVACUUM ){
6018     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6019     if( rc ) goto freepage_out;
6020   }
6021 
6022   /* Now manipulate the actual database free-list structure. There are two
6023   ** possibilities. If the free-list is currently empty, or if the first
6024   ** trunk page in the free-list is full, then this page will become a
6025   ** new free-list trunk page. Otherwise, it will become a leaf of the
6026   ** first trunk page in the current free-list. This block tests if it
6027   ** is possible to add the page as a new free-list leaf.
6028   */
6029   if( nFree!=0 ){
6030     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
6031 
6032     iTrunk = get4byte(&pPage1->aData[32]);
6033     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6034     if( rc!=SQLITE_OK ){
6035       goto freepage_out;
6036     }
6037 
6038     nLeaf = get4byte(&pTrunk->aData[4]);
6039     assert( pBt->usableSize>32 );
6040     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6041       rc = SQLITE_CORRUPT_BKPT;
6042       goto freepage_out;
6043     }
6044     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6045       /* In this case there is room on the trunk page to insert the page
6046       ** being freed as a new leaf.
6047       **
6048       ** Note that the trunk page is not really full until it contains
6049       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6050       ** coded.  But due to a coding error in versions of SQLite prior to
6051       ** 3.6.0, databases with freelist trunk pages holding more than
6052       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
6053       ** to maintain backwards compatibility with older versions of SQLite,
6054       ** we will continue to restrict the number of entries to usableSize/4 - 8
6055       ** for now.  At some point in the future (once everyone has upgraded
6056       ** to 3.6.0 or later) we should consider fixing the conditional above
6057       ** to read "usableSize/4-2" instead of "usableSize/4-8".
6058       **
6059       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6060       ** avoid using the last six entries in the freelist trunk page array in
6061       ** order that database files created by newer versions of SQLite can be
6062       ** read by older versions of SQLite.
6063       */
6064       rc = sqlite3PagerWrite(pTrunk->pDbPage);
6065       if( rc==SQLITE_OK ){
6066         put4byte(&pTrunk->aData[4], nLeaf+1);
6067         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6068         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6069           sqlite3PagerDontWrite(pPage->pDbPage);
6070         }
6071         rc = btreeSetHasContent(pBt, iPage);
6072       }
6073       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
6074       goto freepage_out;
6075     }
6076   }
6077 
6078   /* If control flows to this point, then it was not possible to add the
6079   ** the page being freed as a leaf page of the first trunk in the free-list.
6080   ** Possibly because the free-list is empty, or possibly because the
6081   ** first trunk in the free-list is full. Either way, the page being freed
6082   ** will become the new first trunk page in the free-list.
6083   */
6084   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6085     goto freepage_out;
6086   }
6087   rc = sqlite3PagerWrite(pPage->pDbPage);
6088   if( rc!=SQLITE_OK ){
6089     goto freepage_out;
6090   }
6091   put4byte(pPage->aData, iTrunk);
6092   put4byte(&pPage->aData[4], 0);
6093   put4byte(&pPage1->aData[32], iPage);
6094   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
6095 
6096 freepage_out:
6097   if( pPage ){
6098     pPage->isInit = 0;
6099   }
6100   releasePage(pPage);
6101   releasePage(pTrunk);
6102   return rc;
6103 }
6104 static void freePage(MemPage *pPage, int *pRC){
6105   if( (*pRC)==SQLITE_OK ){
6106     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
6107   }
6108 }
6109 
6110 /*
6111 ** Free any overflow pages associated with the given Cell.  Write the
6112 ** local Cell size (the number of bytes on the original page, omitting
6113 ** overflow) into *pnSize.
6114 */
6115 static int clearCell(
6116   MemPage *pPage,          /* The page that contains the Cell */
6117   unsigned char *pCell,    /* First byte of the Cell */
6118   CellInfo *pInfo          /* Size information about the cell */
6119 ){
6120   BtShared *pBt;
6121   Pgno ovflPgno;
6122   int rc;
6123   int nOvfl;
6124   u32 ovflPageSize;
6125 
6126   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6127   pPage->xParseCell(pPage, pCell, pInfo);
6128   if( pInfo->nLocal==pInfo->nPayload ){
6129     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
6130   }
6131   if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
6132     /* Cell extends past end of page */
6133     return SQLITE_CORRUPT_PGNO(pPage->pgno);
6134   }
6135   ovflPgno = get4byte(pCell + pInfo->nSize - 4);
6136   pBt = pPage->pBt;
6137   assert( pBt->usableSize > 4 );
6138   ovflPageSize = pBt->usableSize - 4;
6139   nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
6140   assert( nOvfl>0 ||
6141     (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
6142   );
6143   while( nOvfl-- ){
6144     Pgno iNext = 0;
6145     MemPage *pOvfl = 0;
6146     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
6147       /* 0 is not a legal page number and page 1 cannot be an
6148       ** overflow page. Therefore if ovflPgno<2 or past the end of the
6149       ** file the database must be corrupt. */
6150       return SQLITE_CORRUPT_BKPT;
6151     }
6152     if( nOvfl ){
6153       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
6154       if( rc ) return rc;
6155     }
6156 
6157     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
6158      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
6159     ){
6160       /* There is no reason any cursor should have an outstanding reference
6161       ** to an overflow page belonging to a cell that is being deleted/updated.
6162       ** So if there exists more than one reference to this page, then it
6163       ** must not really be an overflow page and the database must be corrupt.
6164       ** It is helpful to detect this before calling freePage2(), as
6165       ** freePage2() may zero the page contents if secure-delete mode is
6166       ** enabled. If this 'overflow' page happens to be a page that the
6167       ** caller is iterating through or using in some other way, this
6168       ** can be problematic.
6169       */
6170       rc = SQLITE_CORRUPT_BKPT;
6171     }else{
6172       rc = freePage2(pBt, pOvfl, ovflPgno);
6173     }
6174 
6175     if( pOvfl ){
6176       sqlite3PagerUnref(pOvfl->pDbPage);
6177     }
6178     if( rc ) return rc;
6179     ovflPgno = iNext;
6180   }
6181   return SQLITE_OK;
6182 }
6183 
6184 /*
6185 ** Create the byte sequence used to represent a cell on page pPage
6186 ** and write that byte sequence into pCell[].  Overflow pages are
6187 ** allocated and filled in as necessary.  The calling procedure
6188 ** is responsible for making sure sufficient space has been allocated
6189 ** for pCell[].
6190 **
6191 ** Note that pCell does not necessary need to point to the pPage->aData
6192 ** area.  pCell might point to some temporary storage.  The cell will
6193 ** be constructed in this temporary area then copied into pPage->aData
6194 ** later.
6195 */
6196 static int fillInCell(
6197   MemPage *pPage,                /* The page that contains the cell */
6198   unsigned char *pCell,          /* Complete text of the cell */
6199   const BtreePayload *pX,        /* Payload with which to construct the cell */
6200   int *pnSize                    /* Write cell size here */
6201 ){
6202   int nPayload;
6203   const u8 *pSrc;
6204   int nSrc, n, rc;
6205   int spaceLeft;
6206   MemPage *pOvfl = 0;
6207   MemPage *pToRelease = 0;
6208   unsigned char *pPrior;
6209   unsigned char *pPayload;
6210   BtShared *pBt = pPage->pBt;
6211   Pgno pgnoOvfl = 0;
6212   int nHeader;
6213 
6214   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6215 
6216   /* pPage is not necessarily writeable since pCell might be auxiliary
6217   ** buffer space that is separate from the pPage buffer area */
6218   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
6219             || sqlite3PagerIswriteable(pPage->pDbPage) );
6220 
6221   /* Fill in the header. */
6222   nHeader = pPage->childPtrSize;
6223   if( pPage->intKey ){
6224     nPayload = pX->nData + pX->nZero;
6225     pSrc = pX->pData;
6226     nSrc = pX->nData;
6227     assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
6228     nHeader += putVarint32(&pCell[nHeader], nPayload);
6229     nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
6230   }else{
6231     assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
6232     nSrc = nPayload = (int)pX->nKey;
6233     pSrc = pX->pKey;
6234     nHeader += putVarint32(&pCell[nHeader], nPayload);
6235   }
6236 
6237   /* Fill in the payload */
6238   if( nPayload<=pPage->maxLocal ){
6239     n = nHeader + nPayload;
6240     testcase( n==3 );
6241     testcase( n==4 );
6242     if( n<4 ) n = 4;
6243     *pnSize = n;
6244     spaceLeft = nPayload;
6245     pPrior = pCell;
6246   }else{
6247     int mn = pPage->minLocal;
6248     n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
6249     testcase( n==pPage->maxLocal );
6250     testcase( n==pPage->maxLocal+1 );
6251     if( n > pPage->maxLocal ) n = mn;
6252     spaceLeft = n;
6253     *pnSize = n + nHeader + 4;
6254     pPrior = &pCell[nHeader+n];
6255   }
6256   pPayload = &pCell[nHeader];
6257 
6258   /* At this point variables should be set as follows:
6259   **
6260   **   nPayload           Total payload size in bytes
6261   **   pPayload           Begin writing payload here
6262   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
6263   **                      that means content must spill into overflow pages.
6264   **   *pnSize            Size of the local cell (not counting overflow pages)
6265   **   pPrior             Where to write the pgno of the first overflow page
6266   **
6267   ** Use a call to btreeParseCellPtr() to verify that the values above
6268   ** were computed correctly.
6269   */
6270 #ifdef SQLITE_DEBUG
6271   {
6272     CellInfo info;
6273     pPage->xParseCell(pPage, pCell, &info);
6274     assert( nHeader==(int)(info.pPayload - pCell) );
6275     assert( info.nKey==pX->nKey );
6276     assert( *pnSize == info.nSize );
6277     assert( spaceLeft == info.nLocal );
6278   }
6279 #endif
6280 
6281   /* Write the payload into the local Cell and any extra into overflow pages */
6282   while( nPayload>0 ){
6283     if( spaceLeft==0 ){
6284 #ifndef SQLITE_OMIT_AUTOVACUUM
6285       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
6286       if( pBt->autoVacuum ){
6287         do{
6288           pgnoOvfl++;
6289         } while(
6290           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
6291         );
6292       }
6293 #endif
6294       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
6295 #ifndef SQLITE_OMIT_AUTOVACUUM
6296       /* If the database supports auto-vacuum, and the second or subsequent
6297       ** overflow page is being allocated, add an entry to the pointer-map
6298       ** for that page now.
6299       **
6300       ** If this is the first overflow page, then write a partial entry
6301       ** to the pointer-map. If we write nothing to this pointer-map slot,
6302       ** then the optimistic overflow chain processing in clearCell()
6303       ** may misinterpret the uninitialized values and delete the
6304       ** wrong pages from the database.
6305       */
6306       if( pBt->autoVacuum && rc==SQLITE_OK ){
6307         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
6308         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
6309         if( rc ){
6310           releasePage(pOvfl);
6311         }
6312       }
6313 #endif
6314       if( rc ){
6315         releasePage(pToRelease);
6316         return rc;
6317       }
6318 
6319       /* If pToRelease is not zero than pPrior points into the data area
6320       ** of pToRelease.  Make sure pToRelease is still writeable. */
6321       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6322 
6323       /* If pPrior is part of the data area of pPage, then make sure pPage
6324       ** is still writeable */
6325       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
6326             || sqlite3PagerIswriteable(pPage->pDbPage) );
6327 
6328       put4byte(pPrior, pgnoOvfl);
6329       releasePage(pToRelease);
6330       pToRelease = pOvfl;
6331       pPrior = pOvfl->aData;
6332       put4byte(pPrior, 0);
6333       pPayload = &pOvfl->aData[4];
6334       spaceLeft = pBt->usableSize - 4;
6335     }
6336     n = nPayload;
6337     if( n>spaceLeft ) n = spaceLeft;
6338 
6339     /* If pToRelease is not zero than pPayload points into the data area
6340     ** of pToRelease.  Make sure pToRelease is still writeable. */
6341     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
6342 
6343     /* If pPayload is part of the data area of pPage, then make sure pPage
6344     ** is still writeable */
6345     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
6346             || sqlite3PagerIswriteable(pPage->pDbPage) );
6347 
6348     if( nSrc>0 ){
6349       if( n>nSrc ) n = nSrc;
6350       assert( pSrc );
6351       memcpy(pPayload, pSrc, n);
6352     }else{
6353       memset(pPayload, 0, n);
6354     }
6355     nPayload -= n;
6356     pPayload += n;
6357     pSrc += n;
6358     nSrc -= n;
6359     spaceLeft -= n;
6360   }
6361   releasePage(pToRelease);
6362   return SQLITE_OK;
6363 }
6364 
6365 /*
6366 ** Remove the i-th cell from pPage.  This routine effects pPage only.
6367 ** The cell content is not freed or deallocated.  It is assumed that
6368 ** the cell content has been copied someplace else.  This routine just
6369 ** removes the reference to the cell from pPage.
6370 **
6371 ** "sz" must be the number of bytes in the cell.
6372 */
6373 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
6374   u32 pc;         /* Offset to cell content of cell being deleted */
6375   u8 *data;       /* pPage->aData */
6376   u8 *ptr;        /* Used to move bytes around within data[] */
6377   int rc;         /* The return code */
6378   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
6379 
6380   if( *pRC ) return;
6381   assert( idx>=0 && idx<pPage->nCell );
6382   assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
6383   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6384   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6385   data = pPage->aData;
6386   ptr = &pPage->aCellIdx[2*idx];
6387   pc = get2byte(ptr);
6388   hdr = pPage->hdrOffset;
6389   testcase( pc==get2byte(&data[hdr+5]) );
6390   testcase( pc+sz==pPage->pBt->usableSize );
6391   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
6392     *pRC = SQLITE_CORRUPT_BKPT;
6393     return;
6394   }
6395   rc = freeSpace(pPage, pc, sz);
6396   if( rc ){
6397     *pRC = rc;
6398     return;
6399   }
6400   pPage->nCell--;
6401   if( pPage->nCell==0 ){
6402     memset(&data[hdr+1], 0, 4);
6403     data[hdr+7] = 0;
6404     put2byte(&data[hdr+5], pPage->pBt->usableSize);
6405     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
6406                        - pPage->childPtrSize - 8;
6407   }else{
6408     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
6409     put2byte(&data[hdr+3], pPage->nCell);
6410     pPage->nFree += 2;
6411   }
6412 }
6413 
6414 /*
6415 ** Insert a new cell on pPage at cell index "i".  pCell points to the
6416 ** content of the cell.
6417 **
6418 ** If the cell content will fit on the page, then put it there.  If it
6419 ** will not fit, then make a copy of the cell content into pTemp if
6420 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
6421 ** in pPage->apOvfl[] and make it point to the cell content (either
6422 ** in pTemp or the original pCell) and also record its index.
6423 ** Allocating a new entry in pPage->aCell[] implies that
6424 ** pPage->nOverflow is incremented.
6425 **
6426 ** *pRC must be SQLITE_OK when this routine is called.
6427 */
6428 static void insertCell(
6429   MemPage *pPage,   /* Page into which we are copying */
6430   int i,            /* New cell becomes the i-th cell of the page */
6431   u8 *pCell,        /* Content of the new cell */
6432   int sz,           /* Bytes of content in pCell */
6433   u8 *pTemp,        /* Temp storage space for pCell, if needed */
6434   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
6435   int *pRC          /* Read and write return code from here */
6436 ){
6437   int idx = 0;      /* Where to write new cell content in data[] */
6438   int j;            /* Loop counter */
6439   u8 *data;         /* The content of the whole page */
6440   u8 *pIns;         /* The point in pPage->aCellIdx[] where no cell inserted */
6441 
6442   assert( *pRC==SQLITE_OK );
6443   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
6444   assert( MX_CELL(pPage->pBt)<=10921 );
6445   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
6446   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
6447   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
6448   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6449   /* The cell should normally be sized correctly.  However, when moving a
6450   ** malformed cell from a leaf page to an interior page, if the cell size
6451   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
6452   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
6453   ** the term after the || in the following assert(). */
6454   assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
6455   if( pPage->nOverflow || sz+2>pPage->nFree ){
6456     if( pTemp ){
6457       memcpy(pTemp, pCell, sz);
6458       pCell = pTemp;
6459     }
6460     if( iChild ){
6461       put4byte(pCell, iChild);
6462     }
6463     j = pPage->nOverflow++;
6464     /* Comparison against ArraySize-1 since we hold back one extra slot
6465     ** as a contingency.  In other words, never need more than 3 overflow
6466     ** slots but 4 are allocated, just to be safe. */
6467     assert( j < ArraySize(pPage->apOvfl)-1 );
6468     pPage->apOvfl[j] = pCell;
6469     pPage->aiOvfl[j] = (u16)i;
6470 
6471     /* When multiple overflows occur, they are always sequential and in
6472     ** sorted order.  This invariants arise because multiple overflows can
6473     ** only occur when inserting divider cells into the parent page during
6474     ** balancing, and the dividers are adjacent and sorted.
6475     */
6476     assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
6477     assert( j==0 || i==pPage->aiOvfl[j-1]+1 );   /* Overflows are sequential */
6478   }else{
6479     int rc = sqlite3PagerWrite(pPage->pDbPage);
6480     if( rc!=SQLITE_OK ){
6481       *pRC = rc;
6482       return;
6483     }
6484     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
6485     data = pPage->aData;
6486     assert( &data[pPage->cellOffset]==pPage->aCellIdx );
6487     rc = allocateSpace(pPage, sz, &idx);
6488     if( rc ){ *pRC = rc; return; }
6489     /* The allocateSpace() routine guarantees the following properties
6490     ** if it returns successfully */
6491     assert( idx >= 0 );
6492     assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
6493     assert( idx+sz <= (int)pPage->pBt->usableSize );
6494     pPage->nFree -= (u16)(2 + sz);
6495     memcpy(&data[idx], pCell, sz);
6496     if( iChild ){
6497       put4byte(&data[idx], iChild);
6498     }
6499     pIns = pPage->aCellIdx + i*2;
6500     memmove(pIns+2, pIns, 2*(pPage->nCell - i));
6501     put2byte(pIns, idx);
6502     pPage->nCell++;
6503     /* increment the cell count */
6504     if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
6505     assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
6506 #ifndef SQLITE_OMIT_AUTOVACUUM
6507     if( pPage->pBt->autoVacuum ){
6508       /* The cell may contain a pointer to an overflow page. If so, write
6509       ** the entry for the overflow page into the pointer map.
6510       */
6511       ptrmapPutOvflPtr(pPage, pCell, pRC);
6512     }
6513 #endif
6514   }
6515 }
6516 
6517 /*
6518 ** A CellArray object contains a cache of pointers and sizes for a
6519 ** consecutive sequence of cells that might be held on multiple pages.
6520 */
6521 typedef struct CellArray CellArray;
6522 struct CellArray {
6523   int nCell;              /* Number of cells in apCell[] */
6524   MemPage *pRef;          /* Reference page */
6525   u8 **apCell;            /* All cells begin balanced */
6526   u16 *szCell;            /* Local size of all cells in apCell[] */
6527 };
6528 
6529 /*
6530 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
6531 ** computed.
6532 */
6533 static void populateCellCache(CellArray *p, int idx, int N){
6534   assert( idx>=0 && idx+N<=p->nCell );
6535   while( N>0 ){
6536     assert( p->apCell[idx]!=0 );
6537     if( p->szCell[idx]==0 ){
6538       p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
6539     }else{
6540       assert( CORRUPT_DB ||
6541               p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
6542     }
6543     idx++;
6544     N--;
6545   }
6546 }
6547 
6548 /*
6549 ** Return the size of the Nth element of the cell array
6550 */
6551 static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
6552   assert( N>=0 && N<p->nCell );
6553   assert( p->szCell[N]==0 );
6554   p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
6555   return p->szCell[N];
6556 }
6557 static u16 cachedCellSize(CellArray *p, int N){
6558   assert( N>=0 && N<p->nCell );
6559   if( p->szCell[N] ) return p->szCell[N];
6560   return computeCellSize(p, N);
6561 }
6562 
6563 /*
6564 ** Array apCell[] contains pointers to nCell b-tree page cells. The
6565 ** szCell[] array contains the size in bytes of each cell. This function
6566 ** replaces the current contents of page pPg with the contents of the cell
6567 ** array.
6568 **
6569 ** Some of the cells in apCell[] may currently be stored in pPg. This
6570 ** function works around problems caused by this by making a copy of any
6571 ** such cells before overwriting the page data.
6572 **
6573 ** The MemPage.nFree field is invalidated by this function. It is the
6574 ** responsibility of the caller to set it correctly.
6575 */
6576 static int rebuildPage(
6577   MemPage *pPg,                   /* Edit this page */
6578   int nCell,                      /* Final number of cells on page */
6579   u8 **apCell,                    /* Array of cells */
6580   u16 *szCell                     /* Array of cell sizes */
6581 ){
6582   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
6583   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
6584   const int usableSize = pPg->pBt->usableSize;
6585   u8 * const pEnd = &aData[usableSize];
6586   int i;
6587   u8 *pCellptr = pPg->aCellIdx;
6588   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6589   u8 *pData;
6590 
6591   i = get2byte(&aData[hdr+5]);
6592   memcpy(&pTmp[i], &aData[i], usableSize - i);
6593 
6594   pData = pEnd;
6595   for(i=0; i<nCell; i++){
6596     u8 *pCell = apCell[i];
6597     if( SQLITE_WITHIN(pCell,aData,pEnd) ){
6598       pCell = &pTmp[pCell - aData];
6599     }
6600     pData -= szCell[i];
6601     put2byte(pCellptr, (pData - aData));
6602     pCellptr += 2;
6603     if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
6604     memcpy(pData, pCell, szCell[i]);
6605     assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
6606     testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
6607   }
6608 
6609   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
6610   pPg->nCell = nCell;
6611   pPg->nOverflow = 0;
6612 
6613   put2byte(&aData[hdr+1], 0);
6614   put2byte(&aData[hdr+3], pPg->nCell);
6615   put2byte(&aData[hdr+5], pData - aData);
6616   aData[hdr+7] = 0x00;
6617   return SQLITE_OK;
6618 }
6619 
6620 /*
6621 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6622 ** contains the size in bytes of each such cell. This function attempts to
6623 ** add the cells stored in the array to page pPg. If it cannot (because
6624 ** the page needs to be defragmented before the cells will fit), non-zero
6625 ** is returned. Otherwise, if the cells are added successfully, zero is
6626 ** returned.
6627 **
6628 ** Argument pCellptr points to the first entry in the cell-pointer array
6629 ** (part of page pPg) to populate. After cell apCell[0] is written to the
6630 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
6631 ** cell in the array. It is the responsibility of the caller to ensure
6632 ** that it is safe to overwrite this part of the cell-pointer array.
6633 **
6634 ** When this function is called, *ppData points to the start of the
6635 ** content area on page pPg. If the size of the content area is extended,
6636 ** *ppData is updated to point to the new start of the content area
6637 ** before returning.
6638 **
6639 ** Finally, argument pBegin points to the byte immediately following the
6640 ** end of the space required by this page for the cell-pointer area (for
6641 ** all cells - not just those inserted by the current call). If the content
6642 ** area must be extended to before this point in order to accomodate all
6643 ** cells in apCell[], then the cells do not fit and non-zero is returned.
6644 */
6645 static int pageInsertArray(
6646   MemPage *pPg,                   /* Page to add cells to */
6647   u8 *pBegin,                     /* End of cell-pointer array */
6648   u8 **ppData,                    /* IN/OUT: Page content -area pointer */
6649   u8 *pCellptr,                   /* Pointer to cell-pointer area */
6650   int iFirst,                     /* Index of first cell to add */
6651   int nCell,                      /* Number of cells to add to pPg */
6652   CellArray *pCArray              /* Array of cells */
6653 ){
6654   int i;
6655   u8 *aData = pPg->aData;
6656   u8 *pData = *ppData;
6657   int iEnd = iFirst + nCell;
6658   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
6659   for(i=iFirst; i<iEnd; i++){
6660     int sz, rc;
6661     u8 *pSlot;
6662     sz = cachedCellSize(pCArray, i);
6663     if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
6664       if( (pData - pBegin)<sz ) return 1;
6665       pData -= sz;
6666       pSlot = pData;
6667     }
6668     /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
6669     ** database.  But they might for a corrupt database.  Hence use memmove()
6670     ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
6671     assert( (pSlot+sz)<=pCArray->apCell[i]
6672          || pSlot>=(pCArray->apCell[i]+sz)
6673          || CORRUPT_DB );
6674     memmove(pSlot, pCArray->apCell[i], sz);
6675     put2byte(pCellptr, (pSlot - aData));
6676     pCellptr += 2;
6677   }
6678   *ppData = pData;
6679   return 0;
6680 }
6681 
6682 /*
6683 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
6684 ** contains the size in bytes of each such cell. This function adds the
6685 ** space associated with each cell in the array that is currently stored
6686 ** within the body of pPg to the pPg free-list. The cell-pointers and other
6687 ** fields of the page are not updated.
6688 **
6689 ** This function returns the total number of cells added to the free-list.
6690 */
6691 static int pageFreeArray(
6692   MemPage *pPg,                   /* Page to edit */
6693   int iFirst,                     /* First cell to delete */
6694   int nCell,                      /* Cells to delete */
6695   CellArray *pCArray              /* Array of cells */
6696 ){
6697   u8 * const aData = pPg->aData;
6698   u8 * const pEnd = &aData[pPg->pBt->usableSize];
6699   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
6700   int nRet = 0;
6701   int i;
6702   int iEnd = iFirst + nCell;
6703   u8 *pFree = 0;
6704   int szFree = 0;
6705 
6706   for(i=iFirst; i<iEnd; i++){
6707     u8 *pCell = pCArray->apCell[i];
6708     if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
6709       int sz;
6710       /* No need to use cachedCellSize() here.  The sizes of all cells that
6711       ** are to be freed have already been computing while deciding which
6712       ** cells need freeing */
6713       sz = pCArray->szCell[i];  assert( sz>0 );
6714       if( pFree!=(pCell + sz) ){
6715         if( pFree ){
6716           assert( pFree>aData && (pFree - aData)<65536 );
6717           freeSpace(pPg, (u16)(pFree - aData), szFree);
6718         }
6719         pFree = pCell;
6720         szFree = sz;
6721         if( pFree+sz>pEnd ) return 0;
6722       }else{
6723         pFree = pCell;
6724         szFree += sz;
6725       }
6726       nRet++;
6727     }
6728   }
6729   if( pFree ){
6730     assert( pFree>aData && (pFree - aData)<65536 );
6731     freeSpace(pPg, (u16)(pFree - aData), szFree);
6732   }
6733   return nRet;
6734 }
6735 
6736 /*
6737 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
6738 ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
6739 ** with apCell[iOld].  After balancing, this page should hold nNew cells
6740 ** starting at apCell[iNew].
6741 **
6742 ** This routine makes the necessary adjustments to pPg so that it contains
6743 ** the correct cells after being balanced.
6744 **
6745 ** The pPg->nFree field is invalid when this function returns. It is the
6746 ** responsibility of the caller to set it correctly.
6747 */
6748 static int editPage(
6749   MemPage *pPg,                   /* Edit this page */
6750   int iOld,                       /* Index of first cell currently on page */
6751   int iNew,                       /* Index of new first cell on page */
6752   int nNew,                       /* Final number of cells on page */
6753   CellArray *pCArray              /* Array of cells and sizes */
6754 ){
6755   u8 * const aData = pPg->aData;
6756   const int hdr = pPg->hdrOffset;
6757   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
6758   int nCell = pPg->nCell;       /* Cells stored on pPg */
6759   u8 *pData;
6760   u8 *pCellptr;
6761   int i;
6762   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
6763   int iNewEnd = iNew + nNew;
6764 
6765 #ifdef SQLITE_DEBUG
6766   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
6767   memcpy(pTmp, aData, pPg->pBt->usableSize);
6768 #endif
6769 
6770   /* Remove cells from the start and end of the page */
6771   if( iOld<iNew ){
6772     int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
6773     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
6774     nCell -= nShift;
6775   }
6776   if( iNewEnd < iOldEnd ){
6777     nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
6778   }
6779 
6780   pData = &aData[get2byteNotZero(&aData[hdr+5])];
6781   if( pData<pBegin ) goto editpage_fail;
6782 
6783   /* Add cells to the start of the page */
6784   if( iNew<iOld ){
6785     int nAdd = MIN(nNew,iOld-iNew);
6786     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
6787     pCellptr = pPg->aCellIdx;
6788     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
6789     if( pageInsertArray(
6790           pPg, pBegin, &pData, pCellptr,
6791           iNew, nAdd, pCArray
6792     ) ) goto editpage_fail;
6793     nCell += nAdd;
6794   }
6795 
6796   /* Add any overflow cells */
6797   for(i=0; i<pPg->nOverflow; i++){
6798     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
6799     if( iCell>=0 && iCell<nNew ){
6800       pCellptr = &pPg->aCellIdx[iCell * 2];
6801       memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
6802       nCell++;
6803       if( pageInsertArray(
6804             pPg, pBegin, &pData, pCellptr,
6805             iCell+iNew, 1, pCArray
6806       ) ) goto editpage_fail;
6807     }
6808   }
6809 
6810   /* Append cells to the end of the page */
6811   pCellptr = &pPg->aCellIdx[nCell*2];
6812   if( pageInsertArray(
6813         pPg, pBegin, &pData, pCellptr,
6814         iNew+nCell, nNew-nCell, pCArray
6815   ) ) goto editpage_fail;
6816 
6817   pPg->nCell = nNew;
6818   pPg->nOverflow = 0;
6819 
6820   put2byte(&aData[hdr+3], pPg->nCell);
6821   put2byte(&aData[hdr+5], pData - aData);
6822 
6823 #ifdef SQLITE_DEBUG
6824   for(i=0; i<nNew && !CORRUPT_DB; i++){
6825     u8 *pCell = pCArray->apCell[i+iNew];
6826     int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
6827     if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
6828       pCell = &pTmp[pCell - aData];
6829     }
6830     assert( 0==memcmp(pCell, &aData[iOff],
6831             pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
6832   }
6833 #endif
6834 
6835   return SQLITE_OK;
6836  editpage_fail:
6837   /* Unable to edit this page. Rebuild it from scratch instead. */
6838   populateCellCache(pCArray, iNew, nNew);
6839   return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
6840 }
6841 
6842 /*
6843 ** The following parameters determine how many adjacent pages get involved
6844 ** in a balancing operation.  NN is the number of neighbors on either side
6845 ** of the page that participate in the balancing operation.  NB is the
6846 ** total number of pages that participate, including the target page and
6847 ** NN neighbors on either side.
6848 **
6849 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
6850 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
6851 ** in exchange for a larger degradation in INSERT and UPDATE performance.
6852 ** The value of NN appears to give the best results overall.
6853 */
6854 #define NN 1             /* Number of neighbors on either side of pPage */
6855 #define NB (NN*2+1)      /* Total pages involved in the balance */
6856 
6857 
6858 #ifndef SQLITE_OMIT_QUICKBALANCE
6859 /*
6860 ** This version of balance() handles the common special case where
6861 ** a new entry is being inserted on the extreme right-end of the
6862 ** tree, in other words, when the new entry will become the largest
6863 ** entry in the tree.
6864 **
6865 ** Instead of trying to balance the 3 right-most leaf pages, just add
6866 ** a new page to the right-hand side and put the one new entry in
6867 ** that page.  This leaves the right side of the tree somewhat
6868 ** unbalanced.  But odds are that we will be inserting new entries
6869 ** at the end soon afterwards so the nearly empty page will quickly
6870 ** fill up.  On average.
6871 **
6872 ** pPage is the leaf page which is the right-most page in the tree.
6873 ** pParent is its parent.  pPage must have a single overflow entry
6874 ** which is also the right-most entry on the page.
6875 **
6876 ** The pSpace buffer is used to store a temporary copy of the divider
6877 ** cell that will be inserted into pParent. Such a cell consists of a 4
6878 ** byte page number followed by a variable length integer. In other
6879 ** words, at most 13 bytes. Hence the pSpace buffer must be at
6880 ** least 13 bytes in size.
6881 */
6882 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
6883   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
6884   MemPage *pNew;                       /* Newly allocated page */
6885   int rc;                              /* Return Code */
6886   Pgno pgnoNew;                        /* Page number of pNew */
6887 
6888   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
6889   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6890   assert( pPage->nOverflow==1 );
6891 
6892   /* This error condition is now caught prior to reaching this function */
6893   if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
6894 
6895   /* Allocate a new page. This page will become the right-sibling of
6896   ** pPage. Make the parent page writable, so that the new divider cell
6897   ** may be inserted. If both these operations are successful, proceed.
6898   */
6899   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
6900 
6901   if( rc==SQLITE_OK ){
6902 
6903     u8 *pOut = &pSpace[4];
6904     u8 *pCell = pPage->apOvfl[0];
6905     u16 szCell = pPage->xCellSize(pPage, pCell);
6906     u8 *pStop;
6907 
6908     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
6909     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
6910     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
6911     rc = rebuildPage(pNew, 1, &pCell, &szCell);
6912     if( NEVER(rc) ) return rc;
6913     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
6914 
6915     /* If this is an auto-vacuum database, update the pointer map
6916     ** with entries for the new page, and any pointer from the
6917     ** cell on the page to an overflow page. If either of these
6918     ** operations fails, the return code is set, but the contents
6919     ** of the parent page are still manipulated by thh code below.
6920     ** That is Ok, at this point the parent page is guaranteed to
6921     ** be marked as dirty. Returning an error code will cause a
6922     ** rollback, undoing any changes made to the parent page.
6923     */
6924     if( ISAUTOVACUUM ){
6925       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
6926       if( szCell>pNew->minLocal ){
6927         ptrmapPutOvflPtr(pNew, pCell, &rc);
6928       }
6929     }
6930 
6931     /* Create a divider cell to insert into pParent. The divider cell
6932     ** consists of a 4-byte page number (the page number of pPage) and
6933     ** a variable length key value (which must be the same value as the
6934     ** largest key on pPage).
6935     **
6936     ** To find the largest key value on pPage, first find the right-most
6937     ** cell on pPage. The first two fields of this cell are the
6938     ** record-length (a variable length integer at most 32-bits in size)
6939     ** and the key value (a variable length integer, may have any value).
6940     ** The first of the while(...) loops below skips over the record-length
6941     ** field. The second while(...) loop copies the key value from the
6942     ** cell on pPage into the pSpace buffer.
6943     */
6944     pCell = findCell(pPage, pPage->nCell-1);
6945     pStop = &pCell[9];
6946     while( (*(pCell++)&0x80) && pCell<pStop );
6947     pStop = &pCell[9];
6948     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
6949 
6950     /* Insert the new divider cell into pParent. */
6951     if( rc==SQLITE_OK ){
6952       insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
6953                    0, pPage->pgno, &rc);
6954     }
6955 
6956     /* Set the right-child pointer of pParent to point to the new page. */
6957     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
6958 
6959     /* Release the reference to the new page. */
6960     releasePage(pNew);
6961   }
6962 
6963   return rc;
6964 }
6965 #endif /* SQLITE_OMIT_QUICKBALANCE */
6966 
6967 #if 0
6968 /*
6969 ** This function does not contribute anything to the operation of SQLite.
6970 ** it is sometimes activated temporarily while debugging code responsible
6971 ** for setting pointer-map entries.
6972 */
6973 static int ptrmapCheckPages(MemPage **apPage, int nPage){
6974   int i, j;
6975   for(i=0; i<nPage; i++){
6976     Pgno n;
6977     u8 e;
6978     MemPage *pPage = apPage[i];
6979     BtShared *pBt = pPage->pBt;
6980     assert( pPage->isInit );
6981 
6982     for(j=0; j<pPage->nCell; j++){
6983       CellInfo info;
6984       u8 *z;
6985 
6986       z = findCell(pPage, j);
6987       pPage->xParseCell(pPage, z, &info);
6988       if( info.nLocal<info.nPayload ){
6989         Pgno ovfl = get4byte(&z[info.nSize-4]);
6990         ptrmapGet(pBt, ovfl, &e, &n);
6991         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
6992       }
6993       if( !pPage->leaf ){
6994         Pgno child = get4byte(z);
6995         ptrmapGet(pBt, child, &e, &n);
6996         assert( n==pPage->pgno && e==PTRMAP_BTREE );
6997       }
6998     }
6999     if( !pPage->leaf ){
7000       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7001       ptrmapGet(pBt, child, &e, &n);
7002       assert( n==pPage->pgno && e==PTRMAP_BTREE );
7003     }
7004   }
7005   return 1;
7006 }
7007 #endif
7008 
7009 /*
7010 ** This function is used to copy the contents of the b-tree node stored
7011 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
7012 ** the pointer-map entries for each child page are updated so that the
7013 ** parent page stored in the pointer map is page pTo. If pFrom contained
7014 ** any cells with overflow page pointers, then the corresponding pointer
7015 ** map entries are also updated so that the parent page is page pTo.
7016 **
7017 ** If pFrom is currently carrying any overflow cells (entries in the
7018 ** MemPage.apOvfl[] array), they are not copied to pTo.
7019 **
7020 ** Before returning, page pTo is reinitialized using btreeInitPage().
7021 **
7022 ** The performance of this function is not critical. It is only used by
7023 ** the balance_shallower() and balance_deeper() procedures, neither of
7024 ** which are called often under normal circumstances.
7025 */
7026 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
7027   if( (*pRC)==SQLITE_OK ){
7028     BtShared * const pBt = pFrom->pBt;
7029     u8 * const aFrom = pFrom->aData;
7030     u8 * const aTo = pTo->aData;
7031     int const iFromHdr = pFrom->hdrOffset;
7032     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
7033     int rc;
7034     int iData;
7035 
7036 
7037     assert( pFrom->isInit );
7038     assert( pFrom->nFree>=iToHdr );
7039     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
7040 
7041     /* Copy the b-tree node content from page pFrom to page pTo. */
7042     iData = get2byte(&aFrom[iFromHdr+5]);
7043     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
7044     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
7045 
7046     /* Reinitialize page pTo so that the contents of the MemPage structure
7047     ** match the new data. The initialization of pTo can actually fail under
7048     ** fairly obscure circumstances, even though it is a copy of initialized
7049     ** page pFrom.
7050     */
7051     pTo->isInit = 0;
7052     rc = btreeInitPage(pTo);
7053     if( rc!=SQLITE_OK ){
7054       *pRC = rc;
7055       return;
7056     }
7057 
7058     /* If this is an auto-vacuum database, update the pointer-map entries
7059     ** for any b-tree or overflow pages that pTo now contains the pointers to.
7060     */
7061     if( ISAUTOVACUUM ){
7062       *pRC = setChildPtrmaps(pTo);
7063     }
7064   }
7065 }
7066 
7067 /*
7068 ** This routine redistributes cells on the iParentIdx'th child of pParent
7069 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
7070 ** same amount of free space. Usually a single sibling on either side of the
7071 ** page are used in the balancing, though both siblings might come from one
7072 ** side if the page is the first or last child of its parent. If the page
7073 ** has fewer than 2 siblings (something which can only happen if the page
7074 ** is a root page or a child of a root page) then all available siblings
7075 ** participate in the balancing.
7076 **
7077 ** The number of siblings of the page might be increased or decreased by
7078 ** one or two in an effort to keep pages nearly full but not over full.
7079 **
7080 ** Note that when this routine is called, some of the cells on the page
7081 ** might not actually be stored in MemPage.aData[]. This can happen
7082 ** if the page is overfull. This routine ensures that all cells allocated
7083 ** to the page and its siblings fit into MemPage.aData[] before returning.
7084 **
7085 ** In the course of balancing the page and its siblings, cells may be
7086 ** inserted into or removed from the parent page (pParent). Doing so
7087 ** may cause the parent page to become overfull or underfull. If this
7088 ** happens, it is the responsibility of the caller to invoke the correct
7089 ** balancing routine to fix this problem (see the balance() routine).
7090 **
7091 ** If this routine fails for any reason, it might leave the database
7092 ** in a corrupted state. So if this routine fails, the database should
7093 ** be rolled back.
7094 **
7095 ** The third argument to this function, aOvflSpace, is a pointer to a
7096 ** buffer big enough to hold one page. If while inserting cells into the parent
7097 ** page (pParent) the parent page becomes overfull, this buffer is
7098 ** used to store the parent's overflow cells. Because this function inserts
7099 ** a maximum of four divider cells into the parent page, and the maximum
7100 ** size of a cell stored within an internal node is always less than 1/4
7101 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
7102 ** enough for all overflow cells.
7103 **
7104 ** If aOvflSpace is set to a null pointer, this function returns
7105 ** SQLITE_NOMEM.
7106 */
7107 static int balance_nonroot(
7108   MemPage *pParent,               /* Parent page of siblings being balanced */
7109   int iParentIdx,                 /* Index of "the page" in pParent */
7110   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
7111   int isRoot,                     /* True if pParent is a root-page */
7112   int bBulk                       /* True if this call is part of a bulk load */
7113 ){
7114   BtShared *pBt;               /* The whole database */
7115   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
7116   int nNew = 0;                /* Number of pages in apNew[] */
7117   int nOld;                    /* Number of pages in apOld[] */
7118   int i, j, k;                 /* Loop counters */
7119   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
7120   int rc = SQLITE_OK;          /* The return code */
7121   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
7122   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
7123   int usableSpace;             /* Bytes in pPage beyond the header */
7124   int pageFlags;               /* Value of pPage->aData[0] */
7125   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
7126   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
7127   int szScratch;               /* Size of scratch memory requested */
7128   MemPage *apOld[NB];          /* pPage and up to two siblings */
7129   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
7130   u8 *pRight;                  /* Location in parent of right-sibling pointer */
7131   u8 *apDiv[NB-1];             /* Divider cells in pParent */
7132   int cntNew[NB+2];            /* Index in b.paCell[] of cell after i-th page */
7133   int cntOld[NB+2];            /* Old index in b.apCell[] */
7134   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
7135   u8 *aSpace1;                 /* Space for copies of dividers cells */
7136   Pgno pgno;                   /* Temp var to store a page number in */
7137   u8 abDone[NB+2];             /* True after i'th new page is populated */
7138   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
7139   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
7140   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
7141   CellArray b;                  /* Parsed information on cells being balanced */
7142 
7143   memset(abDone, 0, sizeof(abDone));
7144   b.nCell = 0;
7145   b.apCell = 0;
7146   pBt = pParent->pBt;
7147   assert( sqlite3_mutex_held(pBt->mutex) );
7148   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7149 
7150 #if 0
7151   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
7152 #endif
7153 
7154   /* At this point pParent may have at most one overflow cell. And if
7155   ** this overflow cell is present, it must be the cell with
7156   ** index iParentIdx. This scenario comes about when this function
7157   ** is called (indirectly) from sqlite3BtreeDelete().
7158   */
7159   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
7160   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
7161 
7162   if( !aOvflSpace ){
7163     return SQLITE_NOMEM_BKPT;
7164   }
7165 
7166   /* Find the sibling pages to balance. Also locate the cells in pParent
7167   ** that divide the siblings. An attempt is made to find NN siblings on
7168   ** either side of pPage. More siblings are taken from one side, however,
7169   ** if there are fewer than NN siblings on the other side. If pParent
7170   ** has NB or fewer children then all children of pParent are taken.
7171   **
7172   ** This loop also drops the divider cells from the parent page. This
7173   ** way, the remainder of the function does not have to deal with any
7174   ** overflow cells in the parent page, since if any existed they will
7175   ** have already been removed.
7176   */
7177   i = pParent->nOverflow + pParent->nCell;
7178   if( i<2 ){
7179     nxDiv = 0;
7180   }else{
7181     assert( bBulk==0 || bBulk==1 );
7182     if( iParentIdx==0 ){
7183       nxDiv = 0;
7184     }else if( iParentIdx==i ){
7185       nxDiv = i-2+bBulk;
7186     }else{
7187       nxDiv = iParentIdx-1;
7188     }
7189     i = 2-bBulk;
7190   }
7191   nOld = i+1;
7192   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
7193     pRight = &pParent->aData[pParent->hdrOffset+8];
7194   }else{
7195     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
7196   }
7197   pgno = get4byte(pRight);
7198   while( 1 ){
7199     rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
7200     if( rc ){
7201       memset(apOld, 0, (i+1)*sizeof(MemPage*));
7202       goto balance_cleanup;
7203     }
7204     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
7205     if( (i--)==0 ) break;
7206 
7207     if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
7208       apDiv[i] = pParent->apOvfl[0];
7209       pgno = get4byte(apDiv[i]);
7210       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7211       pParent->nOverflow = 0;
7212     }else{
7213       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
7214       pgno = get4byte(apDiv[i]);
7215       szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
7216 
7217       /* Drop the cell from the parent page. apDiv[i] still points to
7218       ** the cell within the parent, even though it has been dropped.
7219       ** This is safe because dropping a cell only overwrites the first
7220       ** four bytes of it, and this function does not need the first
7221       ** four bytes of the divider cell. So the pointer is safe to use
7222       ** later on.
7223       **
7224       ** But not if we are in secure-delete mode. In secure-delete mode,
7225       ** the dropCell() routine will overwrite the entire cell with zeroes.
7226       ** In this case, temporarily copy the cell into the aOvflSpace[]
7227       ** buffer. It will be copied out again as soon as the aSpace[] buffer
7228       ** is allocated.  */
7229       if( pBt->btsFlags & BTS_FAST_SECURE ){
7230         int iOff;
7231 
7232         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
7233         if( (iOff+szNew[i])>(int)pBt->usableSize ){
7234           rc = SQLITE_CORRUPT_BKPT;
7235           memset(apOld, 0, (i+1)*sizeof(MemPage*));
7236           goto balance_cleanup;
7237         }else{
7238           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
7239           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
7240         }
7241       }
7242       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
7243     }
7244   }
7245 
7246   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
7247   ** alignment */
7248   nMaxCells = (nMaxCells + 3)&~3;
7249 
7250   /*
7251   ** Allocate space for memory structures
7252   */
7253   szScratch =
7254        nMaxCells*sizeof(u8*)                       /* b.apCell */
7255      + nMaxCells*sizeof(u16)                       /* b.szCell */
7256      + pBt->pageSize;                              /* aSpace1 */
7257 
7258   /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
7259   ** that is more than 6 times the database page size. */
7260   assert( szScratch<=6*(int)pBt->pageSize );
7261   b.apCell = sqlite3ScratchMalloc( szScratch );
7262   if( b.apCell==0 ){
7263     rc = SQLITE_NOMEM_BKPT;
7264     goto balance_cleanup;
7265   }
7266   b.szCell = (u16*)&b.apCell[nMaxCells];
7267   aSpace1 = (u8*)&b.szCell[nMaxCells];
7268   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
7269 
7270   /*
7271   ** Load pointers to all cells on sibling pages and the divider cells
7272   ** into the local b.apCell[] array.  Make copies of the divider cells
7273   ** into space obtained from aSpace1[]. The divider cells have already
7274   ** been removed from pParent.
7275   **
7276   ** If the siblings are on leaf pages, then the child pointers of the
7277   ** divider cells are stripped from the cells before they are copied
7278   ** into aSpace1[].  In this way, all cells in b.apCell[] are without
7279   ** child pointers.  If siblings are not leaves, then all cell in
7280   ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
7281   ** are alike.
7282   **
7283   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
7284   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
7285   */
7286   b.pRef = apOld[0];
7287   leafCorrection = b.pRef->leaf*4;
7288   leafData = b.pRef->intKeyLeaf;
7289   for(i=0; i<nOld; i++){
7290     MemPage *pOld = apOld[i];
7291     int limit = pOld->nCell;
7292     u8 *aData = pOld->aData;
7293     u16 maskPage = pOld->maskPage;
7294     u8 *piCell = aData + pOld->cellOffset;
7295     u8 *piEnd;
7296 
7297     /* Verify that all sibling pages are of the same "type" (table-leaf,
7298     ** table-interior, index-leaf, or index-interior).
7299     */
7300     if( pOld->aData[0]!=apOld[0]->aData[0] ){
7301       rc = SQLITE_CORRUPT_BKPT;
7302       goto balance_cleanup;
7303     }
7304 
7305     /* Load b.apCell[] with pointers to all cells in pOld.  If pOld
7306     ** constains overflow cells, include them in the b.apCell[] array
7307     ** in the correct spot.
7308     **
7309     ** Note that when there are multiple overflow cells, it is always the
7310     ** case that they are sequential and adjacent.  This invariant arises
7311     ** because multiple overflows can only occurs when inserting divider
7312     ** cells into a parent on a prior balance, and divider cells are always
7313     ** adjacent and are inserted in order.  There is an assert() tagged
7314     ** with "NOTE 1" in the overflow cell insertion loop to prove this
7315     ** invariant.
7316     **
7317     ** This must be done in advance.  Once the balance starts, the cell
7318     ** offset section of the btree page will be overwritten and we will no
7319     ** long be able to find the cells if a pointer to each cell is not saved
7320     ** first.
7321     */
7322     memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
7323     if( pOld->nOverflow>0 ){
7324       limit = pOld->aiOvfl[0];
7325       for(j=0; j<limit; j++){
7326         b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7327         piCell += 2;
7328         b.nCell++;
7329       }
7330       for(k=0; k<pOld->nOverflow; k++){
7331         assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
7332         b.apCell[b.nCell] = pOld->apOvfl[k];
7333         b.nCell++;
7334       }
7335     }
7336     piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
7337     while( piCell<piEnd ){
7338       assert( b.nCell<nMaxCells );
7339       b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
7340       piCell += 2;
7341       b.nCell++;
7342     }
7343 
7344     cntOld[i] = b.nCell;
7345     if( i<nOld-1 && !leafData){
7346       u16 sz = (u16)szNew[i];
7347       u8 *pTemp;
7348       assert( b.nCell<nMaxCells );
7349       b.szCell[b.nCell] = sz;
7350       pTemp = &aSpace1[iSpace1];
7351       iSpace1 += sz;
7352       assert( sz<=pBt->maxLocal+23 );
7353       assert( iSpace1 <= (int)pBt->pageSize );
7354       memcpy(pTemp, apDiv[i], sz);
7355       b.apCell[b.nCell] = pTemp+leafCorrection;
7356       assert( leafCorrection==0 || leafCorrection==4 );
7357       b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
7358       if( !pOld->leaf ){
7359         assert( leafCorrection==0 );
7360         assert( pOld->hdrOffset==0 );
7361         /* The right pointer of the child page pOld becomes the left
7362         ** pointer of the divider cell */
7363         memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
7364       }else{
7365         assert( leafCorrection==4 );
7366         while( b.szCell[b.nCell]<4 ){
7367           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
7368           ** does exist, pad it with 0x00 bytes. */
7369           assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
7370           assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
7371           aSpace1[iSpace1++] = 0x00;
7372           b.szCell[b.nCell]++;
7373         }
7374       }
7375       b.nCell++;
7376     }
7377   }
7378 
7379   /*
7380   ** Figure out the number of pages needed to hold all b.nCell cells.
7381   ** Store this number in "k".  Also compute szNew[] which is the total
7382   ** size of all cells on the i-th page and cntNew[] which is the index
7383   ** in b.apCell[] of the cell that divides page i from page i+1.
7384   ** cntNew[k] should equal b.nCell.
7385   **
7386   ** Values computed by this block:
7387   **
7388   **           k: The total number of sibling pages
7389   **    szNew[i]: Spaced used on the i-th sibling page.
7390   **   cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
7391   **              the right of the i-th sibling page.
7392   ** usableSpace: Number of bytes of space available on each sibling.
7393   **
7394   */
7395   usableSpace = pBt->usableSize - 12 + leafCorrection;
7396   for(i=0; i<nOld; i++){
7397     MemPage *p = apOld[i];
7398     szNew[i] = usableSpace - p->nFree;
7399     for(j=0; j<p->nOverflow; j++){
7400       szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
7401     }
7402     cntNew[i] = cntOld[i];
7403   }
7404   k = nOld;
7405   for(i=0; i<k; i++){
7406     int sz;
7407     while( szNew[i]>usableSpace ){
7408       if( i+1>=k ){
7409         k = i+2;
7410         if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
7411         szNew[k-1] = 0;
7412         cntNew[k-1] = b.nCell;
7413       }
7414       sz = 2 + cachedCellSize(&b, cntNew[i]-1);
7415       szNew[i] -= sz;
7416       if( !leafData ){
7417         if( cntNew[i]<b.nCell ){
7418           sz = 2 + cachedCellSize(&b, cntNew[i]);
7419         }else{
7420           sz = 0;
7421         }
7422       }
7423       szNew[i+1] += sz;
7424       cntNew[i]--;
7425     }
7426     while( cntNew[i]<b.nCell ){
7427       sz = 2 + cachedCellSize(&b, cntNew[i]);
7428       if( szNew[i]+sz>usableSpace ) break;
7429       szNew[i] += sz;
7430       cntNew[i]++;
7431       if( !leafData ){
7432         if( cntNew[i]<b.nCell ){
7433           sz = 2 + cachedCellSize(&b, cntNew[i]);
7434         }else{
7435           sz = 0;
7436         }
7437       }
7438       szNew[i+1] -= sz;
7439     }
7440     if( cntNew[i]>=b.nCell ){
7441       k = i+1;
7442     }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
7443       rc = SQLITE_CORRUPT_BKPT;
7444       goto balance_cleanup;
7445     }
7446   }
7447 
7448   /*
7449   ** The packing computed by the previous block is biased toward the siblings
7450   ** on the left side (siblings with smaller keys). The left siblings are
7451   ** always nearly full, while the right-most sibling might be nearly empty.
7452   ** The next block of code attempts to adjust the packing of siblings to
7453   ** get a better balance.
7454   **
7455   ** This adjustment is more than an optimization.  The packing above might
7456   ** be so out of balance as to be illegal.  For example, the right-most
7457   ** sibling might be completely empty.  This adjustment is not optional.
7458   */
7459   for(i=k-1; i>0; i--){
7460     int szRight = szNew[i];  /* Size of sibling on the right */
7461     int szLeft = szNew[i-1]; /* Size of sibling on the left */
7462     int r;              /* Index of right-most cell in left sibling */
7463     int d;              /* Index of first cell to the left of right sibling */
7464 
7465     r = cntNew[i-1] - 1;
7466     d = r + 1 - leafData;
7467     (void)cachedCellSize(&b, d);
7468     do{
7469       assert( d<nMaxCells );
7470       assert( r<nMaxCells );
7471       (void)cachedCellSize(&b, r);
7472       if( szRight!=0
7473        && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
7474         break;
7475       }
7476       szRight += b.szCell[d] + 2;
7477       szLeft -= b.szCell[r] + 2;
7478       cntNew[i-1] = r;
7479       r--;
7480       d--;
7481     }while( r>=0 );
7482     szNew[i] = szRight;
7483     szNew[i-1] = szLeft;
7484     if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
7485       rc = SQLITE_CORRUPT_BKPT;
7486       goto balance_cleanup;
7487     }
7488   }
7489 
7490   /* Sanity check:  For a non-corrupt database file one of the follwing
7491   ** must be true:
7492   **    (1) We found one or more cells (cntNew[0])>0), or
7493   **    (2) pPage is a virtual root page.  A virtual root page is when
7494   **        the real root page is page 1 and we are the only child of
7495   **        that page.
7496   */
7497   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
7498   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
7499     apOld[0]->pgno, apOld[0]->nCell,
7500     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
7501     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
7502   ));
7503 
7504   /*
7505   ** Allocate k new pages.  Reuse old pages where possible.
7506   */
7507   pageFlags = apOld[0]->aData[0];
7508   for(i=0; i<k; i++){
7509     MemPage *pNew;
7510     if( i<nOld ){
7511       pNew = apNew[i] = apOld[i];
7512       apOld[i] = 0;
7513       rc = sqlite3PagerWrite(pNew->pDbPage);
7514       nNew++;
7515       if( rc ) goto balance_cleanup;
7516     }else{
7517       assert( i>0 );
7518       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
7519       if( rc ) goto balance_cleanup;
7520       zeroPage(pNew, pageFlags);
7521       apNew[i] = pNew;
7522       nNew++;
7523       cntOld[i] = b.nCell;
7524 
7525       /* Set the pointer-map entry for the new sibling page. */
7526       if( ISAUTOVACUUM ){
7527         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
7528         if( rc!=SQLITE_OK ){
7529           goto balance_cleanup;
7530         }
7531       }
7532     }
7533   }
7534 
7535   /*
7536   ** Reassign page numbers so that the new pages are in ascending order.
7537   ** This helps to keep entries in the disk file in order so that a scan
7538   ** of the table is closer to a linear scan through the file. That in turn
7539   ** helps the operating system to deliver pages from the disk more rapidly.
7540   **
7541   ** An O(n^2) insertion sort algorithm is used, but since n is never more
7542   ** than (NB+2) (a small constant), that should not be a problem.
7543   **
7544   ** When NB==3, this one optimization makes the database about 25% faster
7545   ** for large insertions and deletions.
7546   */
7547   for(i=0; i<nNew; i++){
7548     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
7549     aPgFlags[i] = apNew[i]->pDbPage->flags;
7550     for(j=0; j<i; j++){
7551       if( aPgno[j]==aPgno[i] ){
7552         /* This branch is taken if the set of sibling pages somehow contains
7553         ** duplicate entries. This can happen if the database is corrupt.
7554         ** It would be simpler to detect this as part of the loop below, but
7555         ** we do the detection here in order to avoid populating the pager
7556         ** cache with two separate objects associated with the same
7557         ** page number.  */
7558         assert( CORRUPT_DB );
7559         rc = SQLITE_CORRUPT_BKPT;
7560         goto balance_cleanup;
7561       }
7562     }
7563   }
7564   for(i=0; i<nNew; i++){
7565     int iBest = 0;                /* aPgno[] index of page number to use */
7566     for(j=1; j<nNew; j++){
7567       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
7568     }
7569     pgno = aPgOrder[iBest];
7570     aPgOrder[iBest] = 0xffffffff;
7571     if( iBest!=i ){
7572       if( iBest>i ){
7573         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
7574       }
7575       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
7576       apNew[i]->pgno = pgno;
7577     }
7578   }
7579 
7580   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
7581          "%d(%d nc=%d) %d(%d nc=%d)\n",
7582     apNew[0]->pgno, szNew[0], cntNew[0],
7583     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
7584     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
7585     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
7586     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
7587     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
7588     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
7589     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
7590     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
7591   ));
7592 
7593   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7594   put4byte(pRight, apNew[nNew-1]->pgno);
7595 
7596   /* If the sibling pages are not leaves, ensure that the right-child pointer
7597   ** of the right-most new sibling page is set to the value that was
7598   ** originally in the same field of the right-most old sibling page. */
7599   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
7600     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
7601     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
7602   }
7603 
7604   /* Make any required updates to pointer map entries associated with
7605   ** cells stored on sibling pages following the balance operation. Pointer
7606   ** map entries associated with divider cells are set by the insertCell()
7607   ** routine. The associated pointer map entries are:
7608   **
7609   **   a) if the cell contains a reference to an overflow chain, the
7610   **      entry associated with the first page in the overflow chain, and
7611   **
7612   **   b) if the sibling pages are not leaves, the child page associated
7613   **      with the cell.
7614   **
7615   ** If the sibling pages are not leaves, then the pointer map entry
7616   ** associated with the right-child of each sibling may also need to be
7617   ** updated. This happens below, after the sibling pages have been
7618   ** populated, not here.
7619   */
7620   if( ISAUTOVACUUM ){
7621     MemPage *pNew = apNew[0];
7622     u8 *aOld = pNew->aData;
7623     int cntOldNext = pNew->nCell + pNew->nOverflow;
7624     int usableSize = pBt->usableSize;
7625     int iNew = 0;
7626     int iOld = 0;
7627 
7628     for(i=0; i<b.nCell; i++){
7629       u8 *pCell = b.apCell[i];
7630       if( i==cntOldNext ){
7631         MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
7632         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
7633         aOld = pOld->aData;
7634       }
7635       if( i==cntNew[iNew] ){
7636         pNew = apNew[++iNew];
7637         if( !leafData ) continue;
7638       }
7639 
7640       /* Cell pCell is destined for new sibling page pNew. Originally, it
7641       ** was either part of sibling page iOld (possibly an overflow cell),
7642       ** or else the divider cell to the left of sibling page iOld. So,
7643       ** if sibling page iOld had the same page number as pNew, and if
7644       ** pCell really was a part of sibling page iOld (not a divider or
7645       ** overflow cell), we can skip updating the pointer map entries.  */
7646       if( iOld>=nNew
7647        || pNew->pgno!=aPgno[iOld]
7648        || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
7649       ){
7650         if( !leafCorrection ){
7651           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
7652         }
7653         if( cachedCellSize(&b,i)>pNew->minLocal ){
7654           ptrmapPutOvflPtr(pNew, pCell, &rc);
7655         }
7656         if( rc ) goto balance_cleanup;
7657       }
7658     }
7659   }
7660 
7661   /* Insert new divider cells into pParent. */
7662   for(i=0; i<nNew-1; i++){
7663     u8 *pCell;
7664     u8 *pTemp;
7665     int sz;
7666     MemPage *pNew = apNew[i];
7667     j = cntNew[i];
7668 
7669     assert( j<nMaxCells );
7670     assert( b.apCell[j]!=0 );
7671     pCell = b.apCell[j];
7672     sz = b.szCell[j] + leafCorrection;
7673     pTemp = &aOvflSpace[iOvflSpace];
7674     if( !pNew->leaf ){
7675       memcpy(&pNew->aData[8], pCell, 4);
7676     }else if( leafData ){
7677       /* If the tree is a leaf-data tree, and the siblings are leaves,
7678       ** then there is no divider cell in b.apCell[]. Instead, the divider
7679       ** cell consists of the integer key for the right-most cell of
7680       ** the sibling-page assembled above only.
7681       */
7682       CellInfo info;
7683       j--;
7684       pNew->xParseCell(pNew, b.apCell[j], &info);
7685       pCell = pTemp;
7686       sz = 4 + putVarint(&pCell[4], info.nKey);
7687       pTemp = 0;
7688     }else{
7689       pCell -= 4;
7690       /* Obscure case for non-leaf-data trees: If the cell at pCell was
7691       ** previously stored on a leaf node, and its reported size was 4
7692       ** bytes, then it may actually be smaller than this
7693       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
7694       ** any cell). But it is important to pass the correct size to
7695       ** insertCell(), so reparse the cell now.
7696       **
7697       ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
7698       ** and WITHOUT ROWID tables with exactly one column which is the
7699       ** primary key.
7700       */
7701       if( b.szCell[j]==4 ){
7702         assert(leafCorrection==4);
7703         sz = pParent->xCellSize(pParent, pCell);
7704       }
7705     }
7706     iOvflSpace += sz;
7707     assert( sz<=pBt->maxLocal+23 );
7708     assert( iOvflSpace <= (int)pBt->pageSize );
7709     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
7710     if( rc!=SQLITE_OK ) goto balance_cleanup;
7711     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
7712   }
7713 
7714   /* Now update the actual sibling pages. The order in which they are updated
7715   ** is important, as this code needs to avoid disrupting any page from which
7716   ** cells may still to be read. In practice, this means:
7717   **
7718   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
7719   **      then it is not safe to update page apNew[iPg] until after
7720   **      the left-hand sibling apNew[iPg-1] has been updated.
7721   **
7722   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
7723   **      then it is not safe to update page apNew[iPg] until after
7724   **      the right-hand sibling apNew[iPg+1] has been updated.
7725   **
7726   ** If neither of the above apply, the page is safe to update.
7727   **
7728   ** The iPg value in the following loop starts at nNew-1 goes down
7729   ** to 0, then back up to nNew-1 again, thus making two passes over
7730   ** the pages.  On the initial downward pass, only condition (1) above
7731   ** needs to be tested because (2) will always be true from the previous
7732   ** step.  On the upward pass, both conditions are always true, so the
7733   ** upwards pass simply processes pages that were missed on the downward
7734   ** pass.
7735   */
7736   for(i=1-nNew; i<nNew; i++){
7737     int iPg = i<0 ? -i : i;
7738     assert( iPg>=0 && iPg<nNew );
7739     if( abDone[iPg] ) continue;         /* Skip pages already processed */
7740     if( i>=0                            /* On the upwards pass, or... */
7741      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
7742     ){
7743       int iNew;
7744       int iOld;
7745       int nNewCell;
7746 
7747       /* Verify condition (1):  If cells are moving left, update iPg
7748       ** only after iPg-1 has already been updated. */
7749       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
7750 
7751       /* Verify condition (2):  If cells are moving right, update iPg
7752       ** only after iPg+1 has already been updated. */
7753       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
7754 
7755       if( iPg==0 ){
7756         iNew = iOld = 0;
7757         nNewCell = cntNew[0];
7758       }else{
7759         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
7760         iNew = cntNew[iPg-1] + !leafData;
7761         nNewCell = cntNew[iPg] - iNew;
7762       }
7763 
7764       rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
7765       if( rc ) goto balance_cleanup;
7766       abDone[iPg]++;
7767       apNew[iPg]->nFree = usableSpace-szNew[iPg];
7768       assert( apNew[iPg]->nOverflow==0 );
7769       assert( apNew[iPg]->nCell==nNewCell );
7770     }
7771   }
7772 
7773   /* All pages have been processed exactly once */
7774   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
7775 
7776   assert( nOld>0 );
7777   assert( nNew>0 );
7778 
7779   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
7780     /* The root page of the b-tree now contains no cells. The only sibling
7781     ** page is the right-child of the parent. Copy the contents of the
7782     ** child page into the parent, decreasing the overall height of the
7783     ** b-tree structure by one. This is described as the "balance-shallower"
7784     ** sub-algorithm in some documentation.
7785     **
7786     ** If this is an auto-vacuum database, the call to copyNodeContent()
7787     ** sets all pointer-map entries corresponding to database image pages
7788     ** for which the pointer is stored within the content being copied.
7789     **
7790     ** It is critical that the child page be defragmented before being
7791     ** copied into the parent, because if the parent is page 1 then it will
7792     ** by smaller than the child due to the database header, and so all the
7793     ** free space needs to be up front.
7794     */
7795     assert( nNew==1 || CORRUPT_DB );
7796     rc = defragmentPage(apNew[0], -1);
7797     testcase( rc!=SQLITE_OK );
7798     assert( apNew[0]->nFree ==
7799         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
7800       || rc!=SQLITE_OK
7801     );
7802     copyNodeContent(apNew[0], pParent, &rc);
7803     freePage(apNew[0], &rc);
7804   }else if( ISAUTOVACUUM && !leafCorrection ){
7805     /* Fix the pointer map entries associated with the right-child of each
7806     ** sibling page. All other pointer map entries have already been taken
7807     ** care of.  */
7808     for(i=0; i<nNew; i++){
7809       u32 key = get4byte(&apNew[i]->aData[8]);
7810       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
7811     }
7812   }
7813 
7814   assert( pParent->isInit );
7815   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
7816           nOld, nNew, b.nCell));
7817 
7818   /* Free any old pages that were not reused as new pages.
7819   */
7820   for(i=nNew; i<nOld; i++){
7821     freePage(apOld[i], &rc);
7822   }
7823 
7824 #if 0
7825   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
7826     /* The ptrmapCheckPages() contains assert() statements that verify that
7827     ** all pointer map pages are set correctly. This is helpful while
7828     ** debugging. This is usually disabled because a corrupt database may
7829     ** cause an assert() statement to fail.  */
7830     ptrmapCheckPages(apNew, nNew);
7831     ptrmapCheckPages(&pParent, 1);
7832   }
7833 #endif
7834 
7835   /*
7836   ** Cleanup before returning.
7837   */
7838 balance_cleanup:
7839   sqlite3ScratchFree(b.apCell);
7840   for(i=0; i<nOld; i++){
7841     releasePage(apOld[i]);
7842   }
7843   for(i=0; i<nNew; i++){
7844     releasePage(apNew[i]);
7845   }
7846 
7847   return rc;
7848 }
7849 
7850 
7851 /*
7852 ** This function is called when the root page of a b-tree structure is
7853 ** overfull (has one or more overflow pages).
7854 **
7855 ** A new child page is allocated and the contents of the current root
7856 ** page, including overflow cells, are copied into the child. The root
7857 ** page is then overwritten to make it an empty page with the right-child
7858 ** pointer pointing to the new page.
7859 **
7860 ** Before returning, all pointer-map entries corresponding to pages
7861 ** that the new child-page now contains pointers to are updated. The
7862 ** entry corresponding to the new right-child pointer of the root
7863 ** page is also updated.
7864 **
7865 ** If successful, *ppChild is set to contain a reference to the child
7866 ** page and SQLITE_OK is returned. In this case the caller is required
7867 ** to call releasePage() on *ppChild exactly once. If an error occurs,
7868 ** an error code is returned and *ppChild is set to 0.
7869 */
7870 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
7871   int rc;                        /* Return value from subprocedures */
7872   MemPage *pChild = 0;           /* Pointer to a new child page */
7873   Pgno pgnoChild = 0;            /* Page number of the new child page */
7874   BtShared *pBt = pRoot->pBt;    /* The BTree */
7875 
7876   assert( pRoot->nOverflow>0 );
7877   assert( sqlite3_mutex_held(pBt->mutex) );
7878 
7879   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
7880   ** page that will become the new right-child of pPage. Copy the contents
7881   ** of the node stored on pRoot into the new child page.
7882   */
7883   rc = sqlite3PagerWrite(pRoot->pDbPage);
7884   if( rc==SQLITE_OK ){
7885     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
7886     copyNodeContent(pRoot, pChild, &rc);
7887     if( ISAUTOVACUUM ){
7888       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
7889     }
7890   }
7891   if( rc ){
7892     *ppChild = 0;
7893     releasePage(pChild);
7894     return rc;
7895   }
7896   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
7897   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
7898   assert( pChild->nCell==pRoot->nCell );
7899 
7900   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
7901 
7902   /* Copy the overflow cells from pRoot to pChild */
7903   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
7904          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
7905   memcpy(pChild->apOvfl, pRoot->apOvfl,
7906          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
7907   pChild->nOverflow = pRoot->nOverflow;
7908 
7909   /* Zero the contents of pRoot. Then install pChild as the right-child. */
7910   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
7911   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
7912 
7913   *ppChild = pChild;
7914   return SQLITE_OK;
7915 }
7916 
7917 /*
7918 ** The page that pCur currently points to has just been modified in
7919 ** some way. This function figures out if this modification means the
7920 ** tree needs to be balanced, and if so calls the appropriate balancing
7921 ** routine. Balancing routines are:
7922 **
7923 **   balance_quick()
7924 **   balance_deeper()
7925 **   balance_nonroot()
7926 */
7927 static int balance(BtCursor *pCur){
7928   int rc = SQLITE_OK;
7929   const int nMin = pCur->pBt->usableSize * 2 / 3;
7930   u8 aBalanceQuickSpace[13];
7931   u8 *pFree = 0;
7932 
7933   VVA_ONLY( int balance_quick_called = 0 );
7934   VVA_ONLY( int balance_deeper_called = 0 );
7935 
7936   do {
7937     int iPage = pCur->iPage;
7938     MemPage *pPage = pCur->apPage[iPage];
7939 
7940     if( iPage==0 ){
7941       if( pPage->nOverflow ){
7942         /* The root page of the b-tree is overfull. In this case call the
7943         ** balance_deeper() function to create a new child for the root-page
7944         ** and copy the current contents of the root-page to it. The
7945         ** next iteration of the do-loop will balance the child page.
7946         */
7947         assert( balance_deeper_called==0 );
7948         VVA_ONLY( balance_deeper_called++ );
7949         rc = balance_deeper(pPage, &pCur->apPage[1]);
7950         if( rc==SQLITE_OK ){
7951           pCur->iPage = 1;
7952           pCur->ix = 0;
7953           pCur->aiIdx[0] = 0;
7954           assert( pCur->apPage[1]->nOverflow );
7955         }
7956       }else{
7957         break;
7958       }
7959     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
7960       break;
7961     }else{
7962       MemPage * const pParent = pCur->apPage[iPage-1];
7963       int const iIdx = pCur->aiIdx[iPage-1];
7964 
7965       rc = sqlite3PagerWrite(pParent->pDbPage);
7966       if( rc==SQLITE_OK ){
7967 #ifndef SQLITE_OMIT_QUICKBALANCE
7968         if( pPage->intKeyLeaf
7969          && pPage->nOverflow==1
7970          && pPage->aiOvfl[0]==pPage->nCell
7971          && pParent->pgno!=1
7972          && pParent->nCell==iIdx
7973         ){
7974           /* Call balance_quick() to create a new sibling of pPage on which
7975           ** to store the overflow cell. balance_quick() inserts a new cell
7976           ** into pParent, which may cause pParent overflow. If this
7977           ** happens, the next iteration of the do-loop will balance pParent
7978           ** use either balance_nonroot() or balance_deeper(). Until this
7979           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
7980           ** buffer.
7981           **
7982           ** The purpose of the following assert() is to check that only a
7983           ** single call to balance_quick() is made for each call to this
7984           ** function. If this were not verified, a subtle bug involving reuse
7985           ** of the aBalanceQuickSpace[] might sneak in.
7986           */
7987           assert( balance_quick_called==0 );
7988           VVA_ONLY( balance_quick_called++ );
7989           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
7990         }else
7991 #endif
7992         {
7993           /* In this case, call balance_nonroot() to redistribute cells
7994           ** between pPage and up to 2 of its sibling pages. This involves
7995           ** modifying the contents of pParent, which may cause pParent to
7996           ** become overfull or underfull. The next iteration of the do-loop
7997           ** will balance the parent page to correct this.
7998           **
7999           ** If the parent page becomes overfull, the overflow cell or cells
8000           ** are stored in the pSpace buffer allocated immediately below.
8001           ** A subsequent iteration of the do-loop will deal with this by
8002           ** calling balance_nonroot() (balance_deeper() may be called first,
8003           ** but it doesn't deal with overflow cells - just moves them to a
8004           ** different page). Once this subsequent call to balance_nonroot()
8005           ** has completed, it is safe to release the pSpace buffer used by
8006           ** the previous call, as the overflow cell data will have been
8007           ** copied either into the body of a database page or into the new
8008           ** pSpace buffer passed to the latter call to balance_nonroot().
8009           */
8010           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
8011           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
8012                                pCur->hints&BTREE_BULKLOAD);
8013           if( pFree ){
8014             /* If pFree is not NULL, it points to the pSpace buffer used
8015             ** by a previous call to balance_nonroot(). Its contents are
8016             ** now stored either on real database pages or within the
8017             ** new pSpace buffer, so it may be safely freed here. */
8018             sqlite3PageFree(pFree);
8019           }
8020 
8021           /* The pSpace buffer will be freed after the next call to
8022           ** balance_nonroot(), or just before this function returns, whichever
8023           ** comes first. */
8024           pFree = pSpace;
8025         }
8026       }
8027 
8028       pPage->nOverflow = 0;
8029 
8030       /* The next iteration of the do-loop balances the parent page. */
8031       releasePage(pPage);
8032       pCur->iPage--;
8033       assert( pCur->iPage>=0 );
8034     }
8035   }while( rc==SQLITE_OK );
8036 
8037   if( pFree ){
8038     sqlite3PageFree(pFree);
8039   }
8040   return rc;
8041 }
8042 
8043 
8044 /*
8045 ** Insert a new record into the BTree.  The content of the new record
8046 ** is described by the pX object.  The pCur cursor is used only to
8047 ** define what table the record should be inserted into, and is left
8048 ** pointing at a random location.
8049 **
8050 ** For a table btree (used for rowid tables), only the pX.nKey value of
8051 ** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
8052 ** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
8053 ** hold the content of the row.
8054 **
8055 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
8056 ** key is an arbitrary byte sequence stored in pX.pKey,nKey.  The
8057 ** pX.pData,nData,nZero fields must be zero.
8058 **
8059 ** If the seekResult parameter is non-zero, then a successful call to
8060 ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
8061 ** been performed.  In other words, if seekResult!=0 then the cursor
8062 ** is currently pointing to a cell that will be adjacent to the cell
8063 ** to be inserted.  If seekResult<0 then pCur points to a cell that is
8064 ** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
8065 ** that is larger than (pKey,nKey).
8066 **
8067 ** If seekResult==0, that means pCur is pointing at some unknown location.
8068 ** In that case, this routine must seek the cursor to the correct insertion
8069 ** point for (pKey,nKey) before doing the insertion.  For index btrees,
8070 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
8071 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
8072 ** to decode the key.
8073 */
8074 int sqlite3BtreeInsert(
8075   BtCursor *pCur,                /* Insert data into the table of this cursor */
8076   const BtreePayload *pX,        /* Content of the row to be inserted */
8077   int flags,                     /* True if this is likely an append */
8078   int seekResult                 /* Result of prior MovetoUnpacked() call */
8079 ){
8080   int rc;
8081   int loc = seekResult;          /* -1: before desired location  +1: after */
8082   int szNew = 0;
8083   int idx;
8084   MemPage *pPage;
8085   Btree *p = pCur->pBtree;
8086   BtShared *pBt = p->pBt;
8087   unsigned char *oldCell;
8088   unsigned char *newCell = 0;
8089 
8090   assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
8091 
8092   if( pCur->eState==CURSOR_FAULT ){
8093     assert( pCur->skipNext!=SQLITE_OK );
8094     return pCur->skipNext;
8095   }
8096 
8097   assert( cursorOwnsBtShared(pCur) );
8098   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
8099               && pBt->inTransaction==TRANS_WRITE
8100               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
8101   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8102 
8103   /* Assert that the caller has been consistent. If this cursor was opened
8104   ** expecting an index b-tree, then the caller should be inserting blob
8105   ** keys with no associated data. If the cursor was opened expecting an
8106   ** intkey table, the caller should be inserting integer keys with a
8107   ** blob of associated data.  */
8108   assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
8109 
8110   /* Save the positions of any other cursors open on this table.
8111   **
8112   ** In some cases, the call to btreeMoveto() below is a no-op. For
8113   ** example, when inserting data into a table with auto-generated integer
8114   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
8115   ** integer key to use. It then calls this function to actually insert the
8116   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
8117   ** that the cursor is already where it needs to be and returns without
8118   ** doing any work. To avoid thwarting these optimizations, it is important
8119   ** not to clear the cursor here.
8120   */
8121   if( pCur->curFlags & BTCF_Multiple ){
8122     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8123     if( rc ) return rc;
8124   }
8125 
8126   if( pCur->pKeyInfo==0 ){
8127     assert( pX->pKey==0 );
8128     /* If this is an insert into a table b-tree, invalidate any incrblob
8129     ** cursors open on the row being replaced */
8130     invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
8131 
8132     /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
8133     ** to a row with the same key as the new entry being inserted.  */
8134     assert( (flags & BTREE_SAVEPOSITION)==0 ||
8135             ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
8136 
8137     /* If the cursor is currently on the last row and we are appending a
8138     ** new row onto the end, set the "loc" to avoid an unnecessary
8139     ** btreeMoveto() call */
8140     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
8141       loc = 0;
8142     }else if( loc==0 ){
8143       rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
8144       if( rc ) return rc;
8145     }
8146   }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
8147     if( pX->nMem ){
8148       UnpackedRecord r;
8149       r.pKeyInfo = pCur->pKeyInfo;
8150       r.aMem = pX->aMem;
8151       r.nField = pX->nMem;
8152       r.default_rc = 0;
8153       r.errCode = 0;
8154       r.r1 = 0;
8155       r.r2 = 0;
8156       r.eqSeen = 0;
8157       rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
8158     }else{
8159       rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
8160     }
8161     if( rc ) return rc;
8162   }
8163   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
8164 
8165   pPage = pCur->apPage[pCur->iPage];
8166   assert( pPage->intKey || pX->nKey>=0 );
8167   assert( pPage->leaf || !pPage->intKey );
8168 
8169   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
8170           pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
8171           loc==0 ? "overwrite" : "new entry"));
8172   assert( pPage->isInit );
8173   newCell = pBt->pTmpSpace;
8174   assert( newCell!=0 );
8175   rc = fillInCell(pPage, newCell, pX, &szNew);
8176   if( rc ) goto end_insert;
8177   assert( szNew==pPage->xCellSize(pPage, newCell) );
8178   assert( szNew <= MX_CELL_SIZE(pBt) );
8179   idx = pCur->ix;
8180   if( loc==0 ){
8181     CellInfo info;
8182     assert( idx<pPage->nCell );
8183     rc = sqlite3PagerWrite(pPage->pDbPage);
8184     if( rc ){
8185       goto end_insert;
8186     }
8187     oldCell = findCell(pPage, idx);
8188     if( !pPage->leaf ){
8189       memcpy(newCell, oldCell, 4);
8190     }
8191     rc = clearCell(pPage, oldCell, &info);
8192     if( info.nSize==szNew && info.nLocal==info.nPayload
8193      && (!ISAUTOVACUUM || szNew<pPage->minLocal)
8194     ){
8195       /* Overwrite the old cell with the new if they are the same size.
8196       ** We could also try to do this if the old cell is smaller, then add
8197       ** the leftover space to the free list.  But experiments show that
8198       ** doing that is no faster then skipping this optimization and just
8199       ** calling dropCell() and insertCell().
8200       **
8201       ** This optimization cannot be used on an autovacuum database if the
8202       ** new entry uses overflow pages, as the insertCell() call below is
8203       ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
8204       assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
8205       if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
8206       memcpy(oldCell, newCell, szNew);
8207       return SQLITE_OK;
8208     }
8209     dropCell(pPage, idx, info.nSize, &rc);
8210     if( rc ) goto end_insert;
8211   }else if( loc<0 && pPage->nCell>0 ){
8212     assert( pPage->leaf );
8213     idx = ++pCur->ix;
8214     pCur->curFlags &= ~BTCF_ValidNKey;
8215   }else{
8216     assert( pPage->leaf );
8217   }
8218   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
8219   assert( pPage->nOverflow==0 || rc==SQLITE_OK );
8220   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
8221 
8222   /* If no error has occurred and pPage has an overflow cell, call balance()
8223   ** to redistribute the cells within the tree. Since balance() may move
8224   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
8225   ** variables.
8226   **
8227   ** Previous versions of SQLite called moveToRoot() to move the cursor
8228   ** back to the root page as balance() used to invalidate the contents
8229   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
8230   ** set the cursor state to "invalid". This makes common insert operations
8231   ** slightly faster.
8232   **
8233   ** There is a subtle but important optimization here too. When inserting
8234   ** multiple records into an intkey b-tree using a single cursor (as can
8235   ** happen while processing an "INSERT INTO ... SELECT" statement), it
8236   ** is advantageous to leave the cursor pointing to the last entry in
8237   ** the b-tree if possible. If the cursor is left pointing to the last
8238   ** entry in the table, and the next row inserted has an integer key
8239   ** larger than the largest existing key, it is possible to insert the
8240   ** row without seeking the cursor. This can be a big performance boost.
8241   */
8242   pCur->info.nSize = 0;
8243   if( pPage->nOverflow ){
8244     assert( rc==SQLITE_OK );
8245     pCur->curFlags &= ~(BTCF_ValidNKey);
8246     rc = balance(pCur);
8247 
8248     /* Must make sure nOverflow is reset to zero even if the balance()
8249     ** fails. Internal data structure corruption will result otherwise.
8250     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
8251     ** from trying to save the current position of the cursor.  */
8252     pCur->apPage[pCur->iPage]->nOverflow = 0;
8253     pCur->eState = CURSOR_INVALID;
8254     if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
8255       btreeReleaseAllCursorPages(pCur);
8256       if( pCur->pKeyInfo ){
8257         assert( pCur->pKey==0 );
8258         pCur->pKey = sqlite3Malloc( pX->nKey );
8259         if( pCur->pKey==0 ){
8260           rc = SQLITE_NOMEM;
8261         }else{
8262           memcpy(pCur->pKey, pX->pKey, pX->nKey);
8263         }
8264       }
8265       pCur->eState = CURSOR_REQUIRESEEK;
8266       pCur->nKey = pX->nKey;
8267     }
8268   }
8269   assert( pCur->iPage<0 || pCur->apPage[pCur->iPage]->nOverflow==0 );
8270 
8271 end_insert:
8272   return rc;
8273 }
8274 
8275 /*
8276 ** Delete the entry that the cursor is pointing to.
8277 **
8278 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
8279 ** the cursor is left pointing at an arbitrary location after the delete.
8280 ** But if that bit is set, then the cursor is left in a state such that
8281 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
8282 ** as it would have been on if the call to BtreeDelete() had been omitted.
8283 **
8284 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
8285 ** associated with a single table entry and its indexes.  Only one of those
8286 ** deletes is considered the "primary" delete.  The primary delete occurs
8287 ** on a cursor that is not a BTREE_FORDELETE cursor.  All but one delete
8288 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
8289 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
8290 ** but which might be used by alternative storage engines.
8291 */
8292 int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
8293   Btree *p = pCur->pBtree;
8294   BtShared *pBt = p->pBt;
8295   int rc;                              /* Return code */
8296   MemPage *pPage;                      /* Page to delete cell from */
8297   unsigned char *pCell;                /* Pointer to cell to delete */
8298   int iCellIdx;                        /* Index of cell to delete */
8299   int iCellDepth;                      /* Depth of node containing pCell */
8300   CellInfo info;                       /* Size of the cell being deleted */
8301   int bSkipnext = 0;                   /* Leaf cursor in SKIPNEXT state */
8302   u8 bPreserve = flags & BTREE_SAVEPOSITION;  /* Keep cursor valid */
8303 
8304   assert( cursorOwnsBtShared(pCur) );
8305   assert( pBt->inTransaction==TRANS_WRITE );
8306   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8307   assert( pCur->curFlags & BTCF_WriteFlag );
8308   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
8309   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
8310   assert( pCur->ix<pCur->apPage[pCur->iPage]->nCell );
8311   assert( pCur->eState==CURSOR_VALID );
8312   assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
8313 
8314   iCellDepth = pCur->iPage;
8315   iCellIdx = pCur->ix;
8316   pPage = pCur->apPage[iCellDepth];
8317   pCell = findCell(pPage, iCellIdx);
8318 
8319   /* If the bPreserve flag is set to true, then the cursor position must
8320   ** be preserved following this delete operation. If the current delete
8321   ** will cause a b-tree rebalance, then this is done by saving the cursor
8322   ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
8323   ** returning.
8324   **
8325   ** Or, if the current delete will not cause a rebalance, then the cursor
8326   ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
8327   ** before or after the deleted entry. In this case set bSkipnext to true.  */
8328   if( bPreserve ){
8329     if( !pPage->leaf
8330      || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
8331     ){
8332       /* A b-tree rebalance will be required after deleting this entry.
8333       ** Save the cursor key.  */
8334       rc = saveCursorKey(pCur);
8335       if( rc ) return rc;
8336     }else{
8337       bSkipnext = 1;
8338     }
8339   }
8340 
8341   /* If the page containing the entry to delete is not a leaf page, move
8342   ** the cursor to the largest entry in the tree that is smaller than
8343   ** the entry being deleted. This cell will replace the cell being deleted
8344   ** from the internal node. The 'previous' entry is used for this instead
8345   ** of the 'next' entry, as the previous entry is always a part of the
8346   ** sub-tree headed by the child page of the cell being deleted. This makes
8347   ** balancing the tree following the delete operation easier.  */
8348   if( !pPage->leaf ){
8349     rc = sqlite3BtreePrevious(pCur, 0);
8350     assert( rc!=SQLITE_DONE );
8351     if( rc ) return rc;
8352   }
8353 
8354   /* Save the positions of any other cursors open on this table before
8355   ** making any modifications.  */
8356   if( pCur->curFlags & BTCF_Multiple ){
8357     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
8358     if( rc ) return rc;
8359   }
8360 
8361   /* If this is a delete operation to remove a row from a table b-tree,
8362   ** invalidate any incrblob cursors open on the row being deleted.  */
8363   if( pCur->pKeyInfo==0 ){
8364     invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
8365   }
8366 
8367   /* Make the page containing the entry to be deleted writable. Then free any
8368   ** overflow pages associated with the entry and finally remove the cell
8369   ** itself from within the page.  */
8370   rc = sqlite3PagerWrite(pPage->pDbPage);
8371   if( rc ) return rc;
8372   rc = clearCell(pPage, pCell, &info);
8373   dropCell(pPage, iCellIdx, info.nSize, &rc);
8374   if( rc ) return rc;
8375 
8376   /* If the cell deleted was not located on a leaf page, then the cursor
8377   ** is currently pointing to the largest entry in the sub-tree headed
8378   ** by the child-page of the cell that was just deleted from an internal
8379   ** node. The cell from the leaf node needs to be moved to the internal
8380   ** node to replace the deleted cell.  */
8381   if( !pPage->leaf ){
8382     MemPage *pLeaf = pCur->apPage[pCur->iPage];
8383     int nCell;
8384     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
8385     unsigned char *pTmp;
8386 
8387     pCell = findCell(pLeaf, pLeaf->nCell-1);
8388     if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
8389     nCell = pLeaf->xCellSize(pLeaf, pCell);
8390     assert( MX_CELL_SIZE(pBt) >= nCell );
8391     pTmp = pBt->pTmpSpace;
8392     assert( pTmp!=0 );
8393     rc = sqlite3PagerWrite(pLeaf->pDbPage);
8394     if( rc==SQLITE_OK ){
8395       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
8396     }
8397     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
8398     if( rc ) return rc;
8399   }
8400 
8401   /* Balance the tree. If the entry deleted was located on a leaf page,
8402   ** then the cursor still points to that page. In this case the first
8403   ** call to balance() repairs the tree, and the if(...) condition is
8404   ** never true.
8405   **
8406   ** Otherwise, if the entry deleted was on an internal node page, then
8407   ** pCur is pointing to the leaf page from which a cell was removed to
8408   ** replace the cell deleted from the internal node. This is slightly
8409   ** tricky as the leaf node may be underfull, and the internal node may
8410   ** be either under or overfull. In this case run the balancing algorithm
8411   ** on the leaf node first. If the balance proceeds far enough up the
8412   ** tree that we can be sure that any problem in the internal node has
8413   ** been corrected, so be it. Otherwise, after balancing the leaf node,
8414   ** walk the cursor up the tree to the internal node and balance it as
8415   ** well.  */
8416   rc = balance(pCur);
8417   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
8418     while( pCur->iPage>iCellDepth ){
8419       releasePage(pCur->apPage[pCur->iPage--]);
8420     }
8421     rc = balance(pCur);
8422   }
8423 
8424   if( rc==SQLITE_OK ){
8425     if( bSkipnext ){
8426       assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
8427       assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
8428       assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
8429       pCur->eState = CURSOR_SKIPNEXT;
8430       if( iCellIdx>=pPage->nCell ){
8431         pCur->skipNext = -1;
8432         pCur->ix = pPage->nCell-1;
8433       }else{
8434         pCur->skipNext = 1;
8435       }
8436     }else{
8437       rc = moveToRoot(pCur);
8438       if( bPreserve ){
8439         btreeReleaseAllCursorPages(pCur);
8440         pCur->eState = CURSOR_REQUIRESEEK;
8441       }
8442     }
8443   }
8444   return rc;
8445 }
8446 
8447 /*
8448 ** Create a new BTree table.  Write into *piTable the page
8449 ** number for the root page of the new table.
8450 **
8451 ** The type of type is determined by the flags parameter.  Only the
8452 ** following values of flags are currently in use.  Other values for
8453 ** flags might not work:
8454 **
8455 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
8456 **     BTREE_ZERODATA                  Used for SQL indices
8457 */
8458 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
8459   BtShared *pBt = p->pBt;
8460   MemPage *pRoot;
8461   Pgno pgnoRoot;
8462   int rc;
8463   int ptfFlags;          /* Page-type flage for the root page of new table */
8464 
8465   assert( sqlite3BtreeHoldsMutex(p) );
8466   assert( pBt->inTransaction==TRANS_WRITE );
8467   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
8468 
8469 #ifdef SQLITE_OMIT_AUTOVACUUM
8470   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8471   if( rc ){
8472     return rc;
8473   }
8474 #else
8475   if( pBt->autoVacuum ){
8476     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
8477     MemPage *pPageMove; /* The page to move to. */
8478 
8479     /* Creating a new table may probably require moving an existing database
8480     ** to make room for the new tables root page. In case this page turns
8481     ** out to be an overflow page, delete all overflow page-map caches
8482     ** held by open cursors.
8483     */
8484     invalidateAllOverflowCache(pBt);
8485 
8486     /* Read the value of meta[3] from the database to determine where the
8487     ** root page of the new table should go. meta[3] is the largest root-page
8488     ** created so far, so the new root-page is (meta[3]+1).
8489     */
8490     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
8491     pgnoRoot++;
8492 
8493     /* The new root-page may not be allocated on a pointer-map page, or the
8494     ** PENDING_BYTE page.
8495     */
8496     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
8497         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
8498       pgnoRoot++;
8499     }
8500     assert( pgnoRoot>=3 || CORRUPT_DB );
8501     testcase( pgnoRoot<3 );
8502 
8503     /* Allocate a page. The page that currently resides at pgnoRoot will
8504     ** be moved to the allocated page (unless the allocated page happens
8505     ** to reside at pgnoRoot).
8506     */
8507     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
8508     if( rc!=SQLITE_OK ){
8509       return rc;
8510     }
8511 
8512     if( pgnoMove!=pgnoRoot ){
8513       /* pgnoRoot is the page that will be used for the root-page of
8514       ** the new table (assuming an error did not occur). But we were
8515       ** allocated pgnoMove. If required (i.e. if it was not allocated
8516       ** by extending the file), the current page at position pgnoMove
8517       ** is already journaled.
8518       */
8519       u8 eType = 0;
8520       Pgno iPtrPage = 0;
8521 
8522       /* Save the positions of any open cursors. This is required in
8523       ** case they are holding a reference to an xFetch reference
8524       ** corresponding to page pgnoRoot.  */
8525       rc = saveAllCursors(pBt, 0, 0);
8526       releasePage(pPageMove);
8527       if( rc!=SQLITE_OK ){
8528         return rc;
8529       }
8530 
8531       /* Move the page currently at pgnoRoot to pgnoMove. */
8532       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8533       if( rc!=SQLITE_OK ){
8534         return rc;
8535       }
8536       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
8537       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
8538         rc = SQLITE_CORRUPT_BKPT;
8539       }
8540       if( rc!=SQLITE_OK ){
8541         releasePage(pRoot);
8542         return rc;
8543       }
8544       assert( eType!=PTRMAP_ROOTPAGE );
8545       assert( eType!=PTRMAP_FREEPAGE );
8546       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
8547       releasePage(pRoot);
8548 
8549       /* Obtain the page at pgnoRoot */
8550       if( rc!=SQLITE_OK ){
8551         return rc;
8552       }
8553       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
8554       if( rc!=SQLITE_OK ){
8555         return rc;
8556       }
8557       rc = sqlite3PagerWrite(pRoot->pDbPage);
8558       if( rc!=SQLITE_OK ){
8559         releasePage(pRoot);
8560         return rc;
8561       }
8562     }else{
8563       pRoot = pPageMove;
8564     }
8565 
8566     /* Update the pointer-map and meta-data with the new root-page number. */
8567     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
8568     if( rc ){
8569       releasePage(pRoot);
8570       return rc;
8571     }
8572 
8573     /* When the new root page was allocated, page 1 was made writable in
8574     ** order either to increase the database filesize, or to decrement the
8575     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
8576     */
8577     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
8578     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
8579     if( NEVER(rc) ){
8580       releasePage(pRoot);
8581       return rc;
8582     }
8583 
8584   }else{
8585     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
8586     if( rc ) return rc;
8587   }
8588 #endif
8589   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
8590   if( createTabFlags & BTREE_INTKEY ){
8591     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
8592   }else{
8593     ptfFlags = PTF_ZERODATA | PTF_LEAF;
8594   }
8595   zeroPage(pRoot, ptfFlags);
8596   sqlite3PagerUnref(pRoot->pDbPage);
8597   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
8598   *piTable = (int)pgnoRoot;
8599   return SQLITE_OK;
8600 }
8601 int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
8602   int rc;
8603   sqlite3BtreeEnter(p);
8604   rc = btreeCreateTable(p, piTable, flags);
8605   sqlite3BtreeLeave(p);
8606   return rc;
8607 }
8608 
8609 /*
8610 ** Erase the given database page and all its children.  Return
8611 ** the page to the freelist.
8612 */
8613 static int clearDatabasePage(
8614   BtShared *pBt,           /* The BTree that contains the table */
8615   Pgno pgno,               /* Page number to clear */
8616   int freePageFlag,        /* Deallocate page if true */
8617   int *pnChange            /* Add number of Cells freed to this counter */
8618 ){
8619   MemPage *pPage;
8620   int rc;
8621   unsigned char *pCell;
8622   int i;
8623   int hdr;
8624   CellInfo info;
8625 
8626   assert( sqlite3_mutex_held(pBt->mutex) );
8627   if( pgno>btreePagecount(pBt) ){
8628     return SQLITE_CORRUPT_BKPT;
8629   }
8630   rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
8631   if( rc ) return rc;
8632   if( pPage->bBusy ){
8633     rc = SQLITE_CORRUPT_BKPT;
8634     goto cleardatabasepage_out;
8635   }
8636   pPage->bBusy = 1;
8637   hdr = pPage->hdrOffset;
8638   for(i=0; i<pPage->nCell; i++){
8639     pCell = findCell(pPage, i);
8640     if( !pPage->leaf ){
8641       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
8642       if( rc ) goto cleardatabasepage_out;
8643     }
8644     rc = clearCell(pPage, pCell, &info);
8645     if( rc ) goto cleardatabasepage_out;
8646   }
8647   if( !pPage->leaf ){
8648     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
8649     if( rc ) goto cleardatabasepage_out;
8650   }else if( pnChange ){
8651     assert( pPage->intKey || CORRUPT_DB );
8652     testcase( !pPage->intKey );
8653     *pnChange += pPage->nCell;
8654   }
8655   if( freePageFlag ){
8656     freePage(pPage, &rc);
8657   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
8658     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
8659   }
8660 
8661 cleardatabasepage_out:
8662   pPage->bBusy = 0;
8663   releasePage(pPage);
8664   return rc;
8665 }
8666 
8667 /*
8668 ** Delete all information from a single table in the database.  iTable is
8669 ** the page number of the root of the table.  After this routine returns,
8670 ** the root page is empty, but still exists.
8671 **
8672 ** This routine will fail with SQLITE_LOCKED if there are any open
8673 ** read cursors on the table.  Open write cursors are moved to the
8674 ** root of the table.
8675 **
8676 ** If pnChange is not NULL, then table iTable must be an intkey table. The
8677 ** integer value pointed to by pnChange is incremented by the number of
8678 ** entries in the table.
8679 */
8680 int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
8681   int rc;
8682   BtShared *pBt = p->pBt;
8683   sqlite3BtreeEnter(p);
8684   assert( p->inTrans==TRANS_WRITE );
8685 
8686   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
8687 
8688   if( SQLITE_OK==rc ){
8689     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
8690     ** is the root of a table b-tree - if it is not, the following call is
8691     ** a no-op).  */
8692     invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
8693     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
8694   }
8695   sqlite3BtreeLeave(p);
8696   return rc;
8697 }
8698 
8699 /*
8700 ** Delete all information from the single table that pCur is open on.
8701 **
8702 ** This routine only work for pCur on an ephemeral table.
8703 */
8704 int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
8705   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
8706 }
8707 
8708 /*
8709 ** Erase all information in a table and add the root of the table to
8710 ** the freelist.  Except, the root of the principle table (the one on
8711 ** page 1) is never added to the freelist.
8712 **
8713 ** This routine will fail with SQLITE_LOCKED if there are any open
8714 ** cursors on the table.
8715 **
8716 ** If AUTOVACUUM is enabled and the page at iTable is not the last
8717 ** root page in the database file, then the last root page
8718 ** in the database file is moved into the slot formerly occupied by
8719 ** iTable and that last slot formerly occupied by the last root page
8720 ** is added to the freelist instead of iTable.  In this say, all
8721 ** root pages are kept at the beginning of the database file, which
8722 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
8723 ** page number that used to be the last root page in the file before
8724 ** the move.  If no page gets moved, *piMoved is set to 0.
8725 ** The last root page is recorded in meta[3] and the value of
8726 ** meta[3] is updated by this procedure.
8727 */
8728 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
8729   int rc;
8730   MemPage *pPage = 0;
8731   BtShared *pBt = p->pBt;
8732 
8733   assert( sqlite3BtreeHoldsMutex(p) );
8734   assert( p->inTrans==TRANS_WRITE );
8735   assert( iTable>=2 );
8736 
8737   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
8738   if( rc ) return rc;
8739   rc = sqlite3BtreeClearTable(p, iTable, 0);
8740   if( rc ){
8741     releasePage(pPage);
8742     return rc;
8743   }
8744 
8745   *piMoved = 0;
8746 
8747 #ifdef SQLITE_OMIT_AUTOVACUUM
8748   freePage(pPage, &rc);
8749   releasePage(pPage);
8750 #else
8751   if( pBt->autoVacuum ){
8752     Pgno maxRootPgno;
8753     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
8754 
8755     if( iTable==maxRootPgno ){
8756       /* If the table being dropped is the table with the largest root-page
8757       ** number in the database, put the root page on the free list.
8758       */
8759       freePage(pPage, &rc);
8760       releasePage(pPage);
8761       if( rc!=SQLITE_OK ){
8762         return rc;
8763       }
8764     }else{
8765       /* The table being dropped does not have the largest root-page
8766       ** number in the database. So move the page that does into the
8767       ** gap left by the deleted root-page.
8768       */
8769       MemPage *pMove;
8770       releasePage(pPage);
8771       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
8772       if( rc!=SQLITE_OK ){
8773         return rc;
8774       }
8775       rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
8776       releasePage(pMove);
8777       if( rc!=SQLITE_OK ){
8778         return rc;
8779       }
8780       pMove = 0;
8781       rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
8782       freePage(pMove, &rc);
8783       releasePage(pMove);
8784       if( rc!=SQLITE_OK ){
8785         return rc;
8786       }
8787       *piMoved = maxRootPgno;
8788     }
8789 
8790     /* Set the new 'max-root-page' value in the database header. This
8791     ** is the old value less one, less one more if that happens to
8792     ** be a root-page number, less one again if that is the
8793     ** PENDING_BYTE_PAGE.
8794     */
8795     maxRootPgno--;
8796     while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
8797            || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
8798       maxRootPgno--;
8799     }
8800     assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
8801 
8802     rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
8803   }else{
8804     freePage(pPage, &rc);
8805     releasePage(pPage);
8806   }
8807 #endif
8808   return rc;
8809 }
8810 int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
8811   int rc;
8812   sqlite3BtreeEnter(p);
8813   rc = btreeDropTable(p, iTable, piMoved);
8814   sqlite3BtreeLeave(p);
8815   return rc;
8816 }
8817 
8818 
8819 /*
8820 ** This function may only be called if the b-tree connection already
8821 ** has a read or write transaction open on the database.
8822 **
8823 ** Read the meta-information out of a database file.  Meta[0]
8824 ** is the number of free pages currently in the database.  Meta[1]
8825 ** through meta[15] are available for use by higher layers.  Meta[0]
8826 ** is read-only, the others are read/write.
8827 **
8828 ** The schema layer numbers meta values differently.  At the schema
8829 ** layer (and the SetCookie and ReadCookie opcodes) the number of
8830 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
8831 **
8832 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
8833 ** of reading the value out of the header, it instead loads the "DataVersion"
8834 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
8835 ** database file.  It is a number computed by the pager.  But its access
8836 ** pattern is the same as header meta values, and so it is convenient to
8837 ** read it from this routine.
8838 */
8839 void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
8840   BtShared *pBt = p->pBt;
8841 
8842   sqlite3BtreeEnter(p);
8843   assert( p->inTrans>TRANS_NONE );
8844   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
8845   assert( pBt->pPage1 );
8846   assert( idx>=0 && idx<=15 );
8847 
8848   if( idx==BTREE_DATA_VERSION ){
8849     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
8850   }else{
8851     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
8852   }
8853 
8854   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
8855   ** database, mark the database as read-only.  */
8856 #ifdef SQLITE_OMIT_AUTOVACUUM
8857   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
8858     pBt->btsFlags |= BTS_READ_ONLY;
8859   }
8860 #endif
8861 
8862   sqlite3BtreeLeave(p);
8863 }
8864 
8865 /*
8866 ** Write meta-information back into the database.  Meta[0] is
8867 ** read-only and may not be written.
8868 */
8869 int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
8870   BtShared *pBt = p->pBt;
8871   unsigned char *pP1;
8872   int rc;
8873   assert( idx>=1 && idx<=15 );
8874   sqlite3BtreeEnter(p);
8875   assert( p->inTrans==TRANS_WRITE );
8876   assert( pBt->pPage1!=0 );
8877   pP1 = pBt->pPage1->aData;
8878   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
8879   if( rc==SQLITE_OK ){
8880     put4byte(&pP1[36 + idx*4], iMeta);
8881 #ifndef SQLITE_OMIT_AUTOVACUUM
8882     if( idx==BTREE_INCR_VACUUM ){
8883       assert( pBt->autoVacuum || iMeta==0 );
8884       assert( iMeta==0 || iMeta==1 );
8885       pBt->incrVacuum = (u8)iMeta;
8886     }
8887 #endif
8888   }
8889   sqlite3BtreeLeave(p);
8890   return rc;
8891 }
8892 
8893 #ifndef SQLITE_OMIT_BTREECOUNT
8894 /*
8895 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
8896 ** number of entries in the b-tree and write the result to *pnEntry.
8897 **
8898 ** SQLITE_OK is returned if the operation is successfully executed.
8899 ** Otherwise, if an error is encountered (i.e. an IO error or database
8900 ** corruption) an SQLite error code is returned.
8901 */
8902 int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
8903   i64 nEntry = 0;                      /* Value to return in *pnEntry */
8904   int rc;                              /* Return code */
8905 
8906   if( pCur->pgnoRoot==0 ){
8907     *pnEntry = 0;
8908     return SQLITE_OK;
8909   }
8910   rc = moveToRoot(pCur);
8911 
8912   /* Unless an error occurs, the following loop runs one iteration for each
8913   ** page in the B-Tree structure (not including overflow pages).
8914   */
8915   while( rc==SQLITE_OK ){
8916     int iIdx;                          /* Index of child node in parent */
8917     MemPage *pPage;                    /* Current page of the b-tree */
8918 
8919     /* If this is a leaf page or the tree is not an int-key tree, then
8920     ** this page contains countable entries. Increment the entry counter
8921     ** accordingly.
8922     */
8923     pPage = pCur->apPage[pCur->iPage];
8924     if( pPage->leaf || !pPage->intKey ){
8925       nEntry += pPage->nCell;
8926     }
8927 
8928     /* pPage is a leaf node. This loop navigates the cursor so that it
8929     ** points to the first interior cell that it points to the parent of
8930     ** the next page in the tree that has not yet been visited. The
8931     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
8932     ** of the page, or to the number of cells in the page if the next page
8933     ** to visit is the right-child of its parent.
8934     **
8935     ** If all pages in the tree have been visited, return SQLITE_OK to the
8936     ** caller.
8937     */
8938     if( pPage->leaf ){
8939       do {
8940         if( pCur->iPage==0 ){
8941           /* All pages of the b-tree have been visited. Return successfully. */
8942           *pnEntry = nEntry;
8943           return moveToRoot(pCur);
8944         }
8945         moveToParent(pCur);
8946       }while ( pCur->ix>=pCur->apPage[pCur->iPage]->nCell );
8947 
8948       pCur->ix++;
8949       pPage = pCur->apPage[pCur->iPage];
8950     }
8951 
8952     /* Descend to the child node of the cell that the cursor currently
8953     ** points at. This is the right-child if (iIdx==pPage->nCell).
8954     */
8955     iIdx = pCur->ix;
8956     if( iIdx==pPage->nCell ){
8957       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
8958     }else{
8959       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
8960     }
8961   }
8962 
8963   /* An error has occurred. Return an error code. */
8964   return rc;
8965 }
8966 #endif
8967 
8968 /*
8969 ** Return the pager associated with a BTree.  This routine is used for
8970 ** testing and debugging only.
8971 */
8972 Pager *sqlite3BtreePager(Btree *p){
8973   return p->pBt->pPager;
8974 }
8975 
8976 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
8977 /*
8978 ** Append a message to the error message string.
8979 */
8980 static void checkAppendMsg(
8981   IntegrityCk *pCheck,
8982   const char *zFormat,
8983   ...
8984 ){
8985   va_list ap;
8986   if( !pCheck->mxErr ) return;
8987   pCheck->mxErr--;
8988   pCheck->nErr++;
8989   va_start(ap, zFormat);
8990   if( pCheck->errMsg.nChar ){
8991     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
8992   }
8993   if( pCheck->zPfx ){
8994     sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
8995   }
8996   sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
8997   va_end(ap);
8998   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
8999     pCheck->mallocFailed = 1;
9000   }
9001 }
9002 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9003 
9004 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9005 
9006 /*
9007 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
9008 ** corresponds to page iPg is already set.
9009 */
9010 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9011   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9012   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
9013 }
9014 
9015 /*
9016 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
9017 */
9018 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
9019   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
9020   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
9021 }
9022 
9023 
9024 /*
9025 ** Add 1 to the reference count for page iPage.  If this is the second
9026 ** reference to the page, add an error message to pCheck->zErrMsg.
9027 ** Return 1 if there are 2 or more references to the page and 0 if
9028 ** if this is the first reference to the page.
9029 **
9030 ** Also check that the page number is in bounds.
9031 */
9032 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
9033   if( iPage==0 ) return 1;
9034   if( iPage>pCheck->nPage ){
9035     checkAppendMsg(pCheck, "invalid page number %d", iPage);
9036     return 1;
9037   }
9038   if( getPageReferenced(pCheck, iPage) ){
9039     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
9040     return 1;
9041   }
9042   setPageReferenced(pCheck, iPage);
9043   return 0;
9044 }
9045 
9046 #ifndef SQLITE_OMIT_AUTOVACUUM
9047 /*
9048 ** Check that the entry in the pointer-map for page iChild maps to
9049 ** page iParent, pointer type ptrType. If not, append an error message
9050 ** to pCheck.
9051 */
9052 static void checkPtrmap(
9053   IntegrityCk *pCheck,   /* Integrity check context */
9054   Pgno iChild,           /* Child page number */
9055   u8 eType,              /* Expected pointer map type */
9056   Pgno iParent           /* Expected pointer map parent page number */
9057 ){
9058   int rc;
9059   u8 ePtrmapType;
9060   Pgno iPtrmapParent;
9061 
9062   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
9063   if( rc!=SQLITE_OK ){
9064     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
9065     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
9066     return;
9067   }
9068 
9069   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
9070     checkAppendMsg(pCheck,
9071       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
9072       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
9073   }
9074 }
9075 #endif
9076 
9077 /*
9078 ** Check the integrity of the freelist or of an overflow page list.
9079 ** Verify that the number of pages on the list is N.
9080 */
9081 static void checkList(
9082   IntegrityCk *pCheck,  /* Integrity checking context */
9083   int isFreeList,       /* True for a freelist.  False for overflow page list */
9084   int iPage,            /* Page number for first page in the list */
9085   int N                 /* Expected number of pages in the list */
9086 ){
9087   int i;
9088   int expected = N;
9089   int iFirst = iPage;
9090   while( N-- > 0 && pCheck->mxErr ){
9091     DbPage *pOvflPage;
9092     unsigned char *pOvflData;
9093     if( iPage<1 ){
9094       checkAppendMsg(pCheck,
9095          "%d of %d pages missing from overflow list starting at %d",
9096           N+1, expected, iFirst);
9097       break;
9098     }
9099     if( checkRef(pCheck, iPage) ) break;
9100     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
9101       checkAppendMsg(pCheck, "failed to get page %d", iPage);
9102       break;
9103     }
9104     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
9105     if( isFreeList ){
9106       int n = get4byte(&pOvflData[4]);
9107 #ifndef SQLITE_OMIT_AUTOVACUUM
9108       if( pCheck->pBt->autoVacuum ){
9109         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
9110       }
9111 #endif
9112       if( n>(int)pCheck->pBt->usableSize/4-2 ){
9113         checkAppendMsg(pCheck,
9114            "freelist leaf count too big on page %d", iPage);
9115         N--;
9116       }else{
9117         for(i=0; i<n; i++){
9118           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
9119 #ifndef SQLITE_OMIT_AUTOVACUUM
9120           if( pCheck->pBt->autoVacuum ){
9121             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
9122           }
9123 #endif
9124           checkRef(pCheck, iFreePage);
9125         }
9126         N -= n;
9127       }
9128     }
9129 #ifndef SQLITE_OMIT_AUTOVACUUM
9130     else{
9131       /* If this database supports auto-vacuum and iPage is not the last
9132       ** page in this overflow list, check that the pointer-map entry for
9133       ** the following page matches iPage.
9134       */
9135       if( pCheck->pBt->autoVacuum && N>0 ){
9136         i = get4byte(pOvflData);
9137         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
9138       }
9139     }
9140 #endif
9141     iPage = get4byte(pOvflData);
9142     sqlite3PagerUnref(pOvflPage);
9143 
9144     if( isFreeList && N<(iPage!=0) ){
9145       checkAppendMsg(pCheck, "free-page count in header is too small");
9146     }
9147   }
9148 }
9149 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9150 
9151 /*
9152 ** An implementation of a min-heap.
9153 **
9154 ** aHeap[0] is the number of elements on the heap.  aHeap[1] is the
9155 ** root element.  The daughter nodes of aHeap[N] are aHeap[N*2]
9156 ** and aHeap[N*2+1].
9157 **
9158 ** The heap property is this:  Every node is less than or equal to both
9159 ** of its daughter nodes.  A consequence of the heap property is that the
9160 ** root node aHeap[1] is always the minimum value currently in the heap.
9161 **
9162 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
9163 ** the heap, preserving the heap property.  The btreeHeapPull() routine
9164 ** removes the root element from the heap (the minimum value in the heap)
9165 ** and then moves other nodes around as necessary to preserve the heap
9166 ** property.
9167 **
9168 ** This heap is used for cell overlap and coverage testing.  Each u32
9169 ** entry represents the span of a cell or freeblock on a btree page.
9170 ** The upper 16 bits are the index of the first byte of a range and the
9171 ** lower 16 bits are the index of the last byte of that range.
9172 */
9173 static void btreeHeapInsert(u32 *aHeap, u32 x){
9174   u32 j, i = ++aHeap[0];
9175   aHeap[i] = x;
9176   while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
9177     x = aHeap[j];
9178     aHeap[j] = aHeap[i];
9179     aHeap[i] = x;
9180     i = j;
9181   }
9182 }
9183 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
9184   u32 j, i, x;
9185   if( (x = aHeap[0])==0 ) return 0;
9186   *pOut = aHeap[1];
9187   aHeap[1] = aHeap[x];
9188   aHeap[x] = 0xffffffff;
9189   aHeap[0]--;
9190   i = 1;
9191   while( (j = i*2)<=aHeap[0] ){
9192     if( aHeap[j]>aHeap[j+1] ) j++;
9193     if( aHeap[i]<aHeap[j] ) break;
9194     x = aHeap[i];
9195     aHeap[i] = aHeap[j];
9196     aHeap[j] = x;
9197     i = j;
9198   }
9199   return 1;
9200 }
9201 
9202 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9203 /*
9204 ** Do various sanity checks on a single page of a tree.  Return
9205 ** the tree depth.  Root pages return 0.  Parents of root pages
9206 ** return 1, and so forth.
9207 **
9208 ** These checks are done:
9209 **
9210 **      1.  Make sure that cells and freeblocks do not overlap
9211 **          but combine to completely cover the page.
9212 **      2.  Make sure integer cell keys are in order.
9213 **      3.  Check the integrity of overflow pages.
9214 **      4.  Recursively call checkTreePage on all children.
9215 **      5.  Verify that the depth of all children is the same.
9216 */
9217 static int checkTreePage(
9218   IntegrityCk *pCheck,  /* Context for the sanity check */
9219   int iPage,            /* Page number of the page to check */
9220   i64 *piMinKey,        /* Write minimum integer primary key here */
9221   i64 maxKey            /* Error if integer primary key greater than this */
9222 ){
9223   MemPage *pPage = 0;      /* The page being analyzed */
9224   int i;                   /* Loop counter */
9225   int rc;                  /* Result code from subroutine call */
9226   int depth = -1, d2;      /* Depth of a subtree */
9227   int pgno;                /* Page number */
9228   int nFrag;               /* Number of fragmented bytes on the page */
9229   int hdr;                 /* Offset to the page header */
9230   int cellStart;           /* Offset to the start of the cell pointer array */
9231   int nCell;               /* Number of cells */
9232   int doCoverageCheck = 1; /* True if cell coverage checking should be done */
9233   int keyCanBeEqual = 1;   /* True if IPK can be equal to maxKey
9234                            ** False if IPK must be strictly less than maxKey */
9235   u8 *data;                /* Page content */
9236   u8 *pCell;               /* Cell content */
9237   u8 *pCellIdx;            /* Next element of the cell pointer array */
9238   BtShared *pBt;           /* The BtShared object that owns pPage */
9239   u32 pc;                  /* Address of a cell */
9240   u32 usableSize;          /* Usable size of the page */
9241   u32 contentOffset;       /* Offset to the start of the cell content area */
9242   u32 *heap = 0;           /* Min-heap used for checking cell coverage */
9243   u32 x, prev = 0;         /* Next and previous entry on the min-heap */
9244   const char *saved_zPfx = pCheck->zPfx;
9245   int saved_v1 = pCheck->v1;
9246   int saved_v2 = pCheck->v2;
9247   u8 savedIsInit = 0;
9248 
9249   /* Check that the page exists
9250   */
9251   pBt = pCheck->pBt;
9252   usableSize = pBt->usableSize;
9253   if( iPage==0 ) return 0;
9254   if( checkRef(pCheck, iPage) ) return 0;
9255   pCheck->zPfx = "Page %d: ";
9256   pCheck->v1 = iPage;
9257   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
9258     checkAppendMsg(pCheck,
9259        "unable to get the page. error code=%d", rc);
9260     goto end_of_check;
9261   }
9262 
9263   /* Clear MemPage.isInit to make sure the corruption detection code in
9264   ** btreeInitPage() is executed.  */
9265   savedIsInit = pPage->isInit;
9266   pPage->isInit = 0;
9267   if( (rc = btreeInitPage(pPage))!=0 ){
9268     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
9269     checkAppendMsg(pCheck,
9270                    "btreeInitPage() returns error code %d", rc);
9271     goto end_of_check;
9272   }
9273   data = pPage->aData;
9274   hdr = pPage->hdrOffset;
9275 
9276   /* Set up for cell analysis */
9277   pCheck->zPfx = "On tree page %d cell %d: ";
9278   contentOffset = get2byteNotZero(&data[hdr+5]);
9279   assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
9280 
9281   /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
9282   ** number of cells on the page. */
9283   nCell = get2byte(&data[hdr+3]);
9284   assert( pPage->nCell==nCell );
9285 
9286   /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
9287   ** immediately follows the b-tree page header. */
9288   cellStart = hdr + 12 - 4*pPage->leaf;
9289   assert( pPage->aCellIdx==&data[cellStart] );
9290   pCellIdx = &data[cellStart + 2*(nCell-1)];
9291 
9292   if( !pPage->leaf ){
9293     /* Analyze the right-child page of internal pages */
9294     pgno = get4byte(&data[hdr+8]);
9295 #ifndef SQLITE_OMIT_AUTOVACUUM
9296     if( pBt->autoVacuum ){
9297       pCheck->zPfx = "On page %d at right child: ";
9298       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9299     }
9300 #endif
9301     depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9302     keyCanBeEqual = 0;
9303   }else{
9304     /* For leaf pages, the coverage check will occur in the same loop
9305     ** as the other cell checks, so initialize the heap.  */
9306     heap = pCheck->heap;
9307     heap[0] = 0;
9308   }
9309 
9310   /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
9311   ** integer offsets to the cell contents. */
9312   for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
9313     CellInfo info;
9314 
9315     /* Check cell size */
9316     pCheck->v2 = i;
9317     assert( pCellIdx==&data[cellStart + i*2] );
9318     pc = get2byteAligned(pCellIdx);
9319     pCellIdx -= 2;
9320     if( pc<contentOffset || pc>usableSize-4 ){
9321       checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
9322                              pc, contentOffset, usableSize-4);
9323       doCoverageCheck = 0;
9324       continue;
9325     }
9326     pCell = &data[pc];
9327     pPage->xParseCell(pPage, pCell, &info);
9328     if( pc+info.nSize>usableSize ){
9329       checkAppendMsg(pCheck, "Extends off end of page");
9330       doCoverageCheck = 0;
9331       continue;
9332     }
9333 
9334     /* Check for integer primary key out of range */
9335     if( pPage->intKey ){
9336       if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
9337         checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
9338       }
9339       maxKey = info.nKey;
9340       keyCanBeEqual = 0;     /* Only the first key on the page may ==maxKey */
9341     }
9342 
9343     /* Check the content overflow list */
9344     if( info.nPayload>info.nLocal ){
9345       int nPage;       /* Number of pages on the overflow chain */
9346       Pgno pgnoOvfl;   /* First page of the overflow chain */
9347       assert( pc + info.nSize - 4 <= usableSize );
9348       nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
9349       pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
9350 #ifndef SQLITE_OMIT_AUTOVACUUM
9351       if( pBt->autoVacuum ){
9352         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
9353       }
9354 #endif
9355       checkList(pCheck, 0, pgnoOvfl, nPage);
9356     }
9357 
9358     if( !pPage->leaf ){
9359       /* Check sanity of left child page for internal pages */
9360       pgno = get4byte(pCell);
9361 #ifndef SQLITE_OMIT_AUTOVACUUM
9362       if( pBt->autoVacuum ){
9363         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
9364       }
9365 #endif
9366       d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
9367       keyCanBeEqual = 0;
9368       if( d2!=depth ){
9369         checkAppendMsg(pCheck, "Child page depth differs");
9370         depth = d2;
9371       }
9372     }else{
9373       /* Populate the coverage-checking heap for leaf pages */
9374       btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
9375     }
9376   }
9377   *piMinKey = maxKey;
9378 
9379   /* Check for complete coverage of the page
9380   */
9381   pCheck->zPfx = 0;
9382   if( doCoverageCheck && pCheck->mxErr>0 ){
9383     /* For leaf pages, the min-heap has already been initialized and the
9384     ** cells have already been inserted.  But for internal pages, that has
9385     ** not yet been done, so do it now */
9386     if( !pPage->leaf ){
9387       heap = pCheck->heap;
9388       heap[0] = 0;
9389       for(i=nCell-1; i>=0; i--){
9390         u32 size;
9391         pc = get2byteAligned(&data[cellStart+i*2]);
9392         size = pPage->xCellSize(pPage, &data[pc]);
9393         btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
9394       }
9395     }
9396     /* Add the freeblocks to the min-heap
9397     **
9398     ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
9399     ** is the offset of the first freeblock, or zero if there are no
9400     ** freeblocks on the page.
9401     */
9402     i = get2byte(&data[hdr+1]);
9403     while( i>0 ){
9404       int size, j;
9405       assert( (u32)i<=usableSize-4 );     /* Enforced by btreeInitPage() */
9406       size = get2byte(&data[i+2]);
9407       assert( (u32)(i+size)<=usableSize );  /* Enforced by btreeInitPage() */
9408       btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
9409       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
9410       ** big-endian integer which is the offset in the b-tree page of the next
9411       ** freeblock in the chain, or zero if the freeblock is the last on the
9412       ** chain. */
9413       j = get2byte(&data[i]);
9414       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
9415       ** increasing offset. */
9416       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
9417       assert( (u32)j<=usableSize-4 );   /* Enforced by btreeInitPage() */
9418       i = j;
9419     }
9420     /* Analyze the min-heap looking for overlap between cells and/or
9421     ** freeblocks, and counting the number of untracked bytes in nFrag.
9422     **
9423     ** Each min-heap entry is of the form:    (start_address<<16)|end_address.
9424     ** There is an implied first entry the covers the page header, the cell
9425     ** pointer index, and the gap between the cell pointer index and the start
9426     ** of cell content.
9427     **
9428     ** The loop below pulls entries from the min-heap in order and compares
9429     ** the start_address against the previous end_address.  If there is an
9430     ** overlap, that means bytes are used multiple times.  If there is a gap,
9431     ** that gap is added to the fragmentation count.
9432     */
9433     nFrag = 0;
9434     prev = contentOffset - 1;   /* Implied first min-heap entry */
9435     while( btreeHeapPull(heap,&x) ){
9436       if( (prev&0xffff)>=(x>>16) ){
9437         checkAppendMsg(pCheck,
9438           "Multiple uses for byte %u of page %d", x>>16, iPage);
9439         break;
9440       }else{
9441         nFrag += (x>>16) - (prev&0xffff) - 1;
9442         prev = x;
9443       }
9444     }
9445     nFrag += usableSize - (prev&0xffff) - 1;
9446     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
9447     ** is stored in the fifth field of the b-tree page header.
9448     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
9449     ** number of fragmented free bytes within the cell content area.
9450     */
9451     if( heap[0]==0 && nFrag!=data[hdr+7] ){
9452       checkAppendMsg(pCheck,
9453           "Fragmentation of %d bytes reported as %d on page %d",
9454           nFrag, data[hdr+7], iPage);
9455     }
9456   }
9457 
9458 end_of_check:
9459   if( !doCoverageCheck ) pPage->isInit = savedIsInit;
9460   releasePage(pPage);
9461   pCheck->zPfx = saved_zPfx;
9462   pCheck->v1 = saved_v1;
9463   pCheck->v2 = saved_v2;
9464   return depth+1;
9465 }
9466 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9467 
9468 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
9469 /*
9470 ** This routine does a complete check of the given BTree file.  aRoot[] is
9471 ** an array of pages numbers were each page number is the root page of
9472 ** a table.  nRoot is the number of entries in aRoot.
9473 **
9474 ** A read-only or read-write transaction must be opened before calling
9475 ** this function.
9476 **
9477 ** Write the number of error seen in *pnErr.  Except for some memory
9478 ** allocation errors,  an error message held in memory obtained from
9479 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
9480 ** returned.  If a memory allocation error occurs, NULL is returned.
9481 */
9482 char *sqlite3BtreeIntegrityCheck(
9483   Btree *p,     /* The btree to be checked */
9484   int *aRoot,   /* An array of root pages numbers for individual trees */
9485   int nRoot,    /* Number of entries in aRoot[] */
9486   int mxErr,    /* Stop reporting errors after this many */
9487   int *pnErr    /* Write number of errors seen to this variable */
9488 ){
9489   Pgno i;
9490   IntegrityCk sCheck;
9491   BtShared *pBt = p->pBt;
9492   int savedDbFlags = pBt->db->flags;
9493   char zErr[100];
9494   VVA_ONLY( int nRef );
9495 
9496   sqlite3BtreeEnter(p);
9497   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
9498   VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
9499   assert( nRef>=0 );
9500   sCheck.pBt = pBt;
9501   sCheck.pPager = pBt->pPager;
9502   sCheck.nPage = btreePagecount(sCheck.pBt);
9503   sCheck.mxErr = mxErr;
9504   sCheck.nErr = 0;
9505   sCheck.mallocFailed = 0;
9506   sCheck.zPfx = 0;
9507   sCheck.v1 = 0;
9508   sCheck.v2 = 0;
9509   sCheck.aPgRef = 0;
9510   sCheck.heap = 0;
9511   sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
9512   sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
9513   if( sCheck.nPage==0 ){
9514     goto integrity_ck_cleanup;
9515   }
9516 
9517   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
9518   if( !sCheck.aPgRef ){
9519     sCheck.mallocFailed = 1;
9520     goto integrity_ck_cleanup;
9521   }
9522   sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
9523   if( sCheck.heap==0 ){
9524     sCheck.mallocFailed = 1;
9525     goto integrity_ck_cleanup;
9526   }
9527 
9528   i = PENDING_BYTE_PAGE(pBt);
9529   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
9530 
9531   /* Check the integrity of the freelist
9532   */
9533   sCheck.zPfx = "Main freelist: ";
9534   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
9535             get4byte(&pBt->pPage1->aData[36]));
9536   sCheck.zPfx = 0;
9537 
9538   /* Check all the tables.
9539   */
9540   testcase( pBt->db->flags & SQLITE_CellSizeCk );
9541   pBt->db->flags &= ~SQLITE_CellSizeCk;
9542   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
9543     i64 notUsed;
9544     if( aRoot[i]==0 ) continue;
9545 #ifndef SQLITE_OMIT_AUTOVACUUM
9546     if( pBt->autoVacuum && aRoot[i]>1 ){
9547       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
9548     }
9549 #endif
9550     checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
9551   }
9552   pBt->db->flags = savedDbFlags;
9553 
9554   /* Make sure every page in the file is referenced
9555   */
9556   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
9557 #ifdef SQLITE_OMIT_AUTOVACUUM
9558     if( getPageReferenced(&sCheck, i)==0 ){
9559       checkAppendMsg(&sCheck, "Page %d is never used", i);
9560     }
9561 #else
9562     /* If the database supports auto-vacuum, make sure no tables contain
9563     ** references to pointer-map pages.
9564     */
9565     if( getPageReferenced(&sCheck, i)==0 &&
9566        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
9567       checkAppendMsg(&sCheck, "Page %d is never used", i);
9568     }
9569     if( getPageReferenced(&sCheck, i)!=0 &&
9570        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
9571       checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
9572     }
9573 #endif
9574   }
9575 
9576   /* Clean  up and report errors.
9577   */
9578 integrity_ck_cleanup:
9579   sqlite3PageFree(sCheck.heap);
9580   sqlite3_free(sCheck.aPgRef);
9581   if( sCheck.mallocFailed ){
9582     sqlite3StrAccumReset(&sCheck.errMsg);
9583     sCheck.nErr++;
9584   }
9585   *pnErr = sCheck.nErr;
9586   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
9587   /* Make sure this analysis did not leave any unref() pages. */
9588   assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
9589   sqlite3BtreeLeave(p);
9590   return sqlite3StrAccumFinish(&sCheck.errMsg);
9591 }
9592 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
9593 
9594 /*
9595 ** Return the full pathname of the underlying database file.  Return
9596 ** an empty string if the database is in-memory or a TEMP database.
9597 **
9598 ** The pager filename is invariant as long as the pager is
9599 ** open so it is safe to access without the BtShared mutex.
9600 */
9601 const char *sqlite3BtreeGetFilename(Btree *p){
9602   assert( p->pBt->pPager!=0 );
9603   return sqlite3PagerFilename(p->pBt->pPager, 1);
9604 }
9605 
9606 /*
9607 ** Return the pathname of the journal file for this database. The return
9608 ** value of this routine is the same regardless of whether the journal file
9609 ** has been created or not.
9610 **
9611 ** The pager journal filename is invariant as long as the pager is
9612 ** open so it is safe to access without the BtShared mutex.
9613 */
9614 const char *sqlite3BtreeGetJournalname(Btree *p){
9615   assert( p->pBt->pPager!=0 );
9616   return sqlite3PagerJournalname(p->pBt->pPager);
9617 }
9618 
9619 /*
9620 ** Return non-zero if a transaction is active.
9621 */
9622 int sqlite3BtreeIsInTrans(Btree *p){
9623   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
9624   return (p && (p->inTrans==TRANS_WRITE));
9625 }
9626 
9627 #ifndef SQLITE_OMIT_WAL
9628 /*
9629 ** Run a checkpoint on the Btree passed as the first argument.
9630 **
9631 ** Return SQLITE_LOCKED if this or any other connection has an open
9632 ** transaction on the shared-cache the argument Btree is connected to.
9633 **
9634 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
9635 */
9636 int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
9637   int rc = SQLITE_OK;
9638   if( p ){
9639     BtShared *pBt = p->pBt;
9640     sqlite3BtreeEnter(p);
9641     if( pBt->inTransaction!=TRANS_NONE ){
9642       rc = SQLITE_LOCKED;
9643     }else{
9644       rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
9645     }
9646     sqlite3BtreeLeave(p);
9647   }
9648   return rc;
9649 }
9650 #endif
9651 
9652 /*
9653 ** Return non-zero if a read (or write) transaction is active.
9654 */
9655 int sqlite3BtreeIsInReadTrans(Btree *p){
9656   assert( p );
9657   assert( sqlite3_mutex_held(p->db->mutex) );
9658   return p->inTrans!=TRANS_NONE;
9659 }
9660 
9661 int sqlite3BtreeIsInBackup(Btree *p){
9662   assert( p );
9663   assert( sqlite3_mutex_held(p->db->mutex) );
9664   return p->nBackup!=0;
9665 }
9666 
9667 /*
9668 ** This function returns a pointer to a blob of memory associated with
9669 ** a single shared-btree. The memory is used by client code for its own
9670 ** purposes (for example, to store a high-level schema associated with
9671 ** the shared-btree). The btree layer manages reference counting issues.
9672 **
9673 ** The first time this is called on a shared-btree, nBytes bytes of memory
9674 ** are allocated, zeroed, and returned to the caller. For each subsequent
9675 ** call the nBytes parameter is ignored and a pointer to the same blob
9676 ** of memory returned.
9677 **
9678 ** If the nBytes parameter is 0 and the blob of memory has not yet been
9679 ** allocated, a null pointer is returned. If the blob has already been
9680 ** allocated, it is returned as normal.
9681 **
9682 ** Just before the shared-btree is closed, the function passed as the
9683 ** xFree argument when the memory allocation was made is invoked on the
9684 ** blob of allocated memory. The xFree function should not call sqlite3_free()
9685 ** on the memory, the btree layer does that.
9686 */
9687 void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
9688   BtShared *pBt = p->pBt;
9689   sqlite3BtreeEnter(p);
9690   if( !pBt->pSchema && nBytes ){
9691     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
9692     pBt->xFreeSchema = xFree;
9693   }
9694   sqlite3BtreeLeave(p);
9695   return pBt->pSchema;
9696 }
9697 
9698 /*
9699 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
9700 ** btree as the argument handle holds an exclusive lock on the
9701 ** sqlite_master table. Otherwise SQLITE_OK.
9702 */
9703 int sqlite3BtreeSchemaLocked(Btree *p){
9704   int rc;
9705   assert( sqlite3_mutex_held(p->db->mutex) );
9706   sqlite3BtreeEnter(p);
9707   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
9708   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
9709   sqlite3BtreeLeave(p);
9710   return rc;
9711 }
9712 
9713 
9714 #ifndef SQLITE_OMIT_SHARED_CACHE
9715 /*
9716 ** Obtain a lock on the table whose root page is iTab.  The
9717 ** lock is a write lock if isWritelock is true or a read lock
9718 ** if it is false.
9719 */
9720 int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
9721   int rc = SQLITE_OK;
9722   assert( p->inTrans!=TRANS_NONE );
9723   if( p->sharable ){
9724     u8 lockType = READ_LOCK + isWriteLock;
9725     assert( READ_LOCK+1==WRITE_LOCK );
9726     assert( isWriteLock==0 || isWriteLock==1 );
9727 
9728     sqlite3BtreeEnter(p);
9729     rc = querySharedCacheTableLock(p, iTab, lockType);
9730     if( rc==SQLITE_OK ){
9731       rc = setSharedCacheTableLock(p, iTab, lockType);
9732     }
9733     sqlite3BtreeLeave(p);
9734   }
9735   return rc;
9736 }
9737 #endif
9738 
9739 #ifndef SQLITE_OMIT_INCRBLOB
9740 /*
9741 ** Argument pCsr must be a cursor opened for writing on an
9742 ** INTKEY table currently pointing at a valid table entry.
9743 ** This function modifies the data stored as part of that entry.
9744 **
9745 ** Only the data content may only be modified, it is not possible to
9746 ** change the length of the data stored. If this function is called with
9747 ** parameters that attempt to write past the end of the existing data,
9748 ** no modifications are made and SQLITE_CORRUPT is returned.
9749 */
9750 int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
9751   int rc;
9752   assert( cursorOwnsBtShared(pCsr) );
9753   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
9754   assert( pCsr->curFlags & BTCF_Incrblob );
9755 
9756   rc = restoreCursorPosition(pCsr);
9757   if( rc!=SQLITE_OK ){
9758     return rc;
9759   }
9760   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
9761   if( pCsr->eState!=CURSOR_VALID ){
9762     return SQLITE_ABORT;
9763   }
9764 
9765   /* Save the positions of all other cursors open on this table. This is
9766   ** required in case any of them are holding references to an xFetch
9767   ** version of the b-tree page modified by the accessPayload call below.
9768   **
9769   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
9770   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
9771   ** saveAllCursors can only return SQLITE_OK.
9772   */
9773   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
9774   assert( rc==SQLITE_OK );
9775 
9776   /* Check some assumptions:
9777   **   (a) the cursor is open for writing,
9778   **   (b) there is a read/write transaction open,
9779   **   (c) the connection holds a write-lock on the table (if required),
9780   **   (d) there are no conflicting read-locks, and
9781   **   (e) the cursor points at a valid row of an intKey table.
9782   */
9783   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
9784     return SQLITE_READONLY;
9785   }
9786   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
9787               && pCsr->pBt->inTransaction==TRANS_WRITE );
9788   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
9789   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
9790   assert( pCsr->apPage[pCsr->iPage]->intKey );
9791 
9792   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
9793 }
9794 
9795 /*
9796 ** Mark this cursor as an incremental blob cursor.
9797 */
9798 void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
9799   pCur->curFlags |= BTCF_Incrblob;
9800   pCur->pBtree->hasIncrblobCur = 1;
9801 }
9802 #endif
9803 
9804 /*
9805 ** Set both the "read version" (single byte at byte offset 18) and
9806 ** "write version" (single byte at byte offset 19) fields in the database
9807 ** header to iVersion.
9808 */
9809 int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
9810   BtShared *pBt = pBtree->pBt;
9811   int rc;                         /* Return code */
9812 
9813   assert( iVersion==1 || iVersion==2 );
9814 
9815   /* If setting the version fields to 1, do not automatically open the
9816   ** WAL connection, even if the version fields are currently set to 2.
9817   */
9818   pBt->btsFlags &= ~BTS_NO_WAL;
9819   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
9820 
9821   rc = sqlite3BtreeBeginTrans(pBtree, 0);
9822   if( rc==SQLITE_OK ){
9823     u8 *aData = pBt->pPage1->aData;
9824     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
9825       rc = sqlite3BtreeBeginTrans(pBtree, 2);
9826       if( rc==SQLITE_OK ){
9827         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
9828         if( rc==SQLITE_OK ){
9829           aData[18] = (u8)iVersion;
9830           aData[19] = (u8)iVersion;
9831         }
9832       }
9833     }
9834   }
9835 
9836   pBt->btsFlags &= ~BTS_NO_WAL;
9837   return rc;
9838 }
9839 
9840 /*
9841 ** Return true if the cursor has a hint specified.  This routine is
9842 ** only used from within assert() statements
9843 */
9844 int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
9845   return (pCsr->hints & mask)!=0;
9846 }
9847 
9848 /*
9849 ** Return true if the given Btree is read-only.
9850 */
9851 int sqlite3BtreeIsReadonly(Btree *p){
9852   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
9853 }
9854 
9855 /*
9856 ** Return the size of the header added to each page by this module.
9857 */
9858 int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
9859 
9860 #if !defined(SQLITE_OMIT_SHARED_CACHE)
9861 /*
9862 ** Return true if the Btree passed as the only argument is sharable.
9863 */
9864 int sqlite3BtreeSharable(Btree *p){
9865   return p->sharable;
9866 }
9867 
9868 /*
9869 ** Return the number of connections to the BtShared object accessed by
9870 ** the Btree handle passed as the only argument. For private caches
9871 ** this is always 1. For shared caches it may be 1 or greater.
9872 */
9873 int sqlite3BtreeConnectionCount(Btree *p){
9874   testcase( p->sharable );
9875   return p->pBt->nRef;
9876 }
9877 #endif
9878