interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / btree.c

11671 lines · 408604 bytes Raw Blame History
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** Suppress false-positive compiler warnings from GCC. Warnings are
20** re-enabled at the bottom of this source file.
21*/
22#if defined(__GNUC__) && __GNUC__>=11
23# pragma GCC diagnostic push
24# pragma GCC diagnostic ignored "-Wstringop-overread"
25# pragma GCC diagnostic ignored "-Wstringop-overflow"
26#endif
27
28/*
29** The header string that appears at the beginning of every
30** SQLite database.
31*/
32static const char zMagicHeader[] = SQLITE_FILE_HEADER;
33
34/*
35** Set this global variable to 1 to enable tracing using the TRACE
36** macro.
37*/
38#if 0
39int sqlite3BtreeTrace=1; /* True to enable tracing */
40# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
41#else
42# define TRACE(X)
43#endif
44
45/*
46** Extract a 2-byte big-endian integer from an array of unsigned bytes.
47** But if the value is zero, make it 65536.
48**
49** This routine is used to extract the "offset to cell content area" value
50** from the header of a btree page. If the page size is 65536 and the page
51** is empty, the offset should be 65536, but the 2-byte value stores zero.
52** This routine makes the necessary adjustment to 65536.
53*/
54#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
55
56/*
57** Values passed as the 5th argument to allocateBtreePage()
58*/
59#define BTALLOC_ANY 0 /* Allocate any page */
60#define BTALLOC_EXACT 1 /* Allocate exact page if possible */
61#define BTALLOC_LE 2 /* Allocate any page <= the parameter */
62
63/*
64** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
65** defined, or 0 if it is. For example:
66**
67** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
68*/
69#ifndef SQLITE_OMIT_AUTOVACUUM
70#define IfNotOmitAV(expr) (expr)
71#else
72#define IfNotOmitAV(expr) 0
73#endif
74
75#ifndef SQLITE_OMIT_SHARED_CACHE
76/*
77** A list of BtShared objects that are eligible for participation
78** in shared cache. This variable has file scope during normal builds,
79** but the test harness needs to access it so we make it global for
80** test builds.
81**
82** Access to this variable is protected by SQLITE_MUTEX_STATIC_MAIN.
83*/
84#ifdef SQLITE_TEST
85BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
86#else
87static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
88#endif
89#endif /* SQLITE_OMIT_SHARED_CACHE */
90
91#ifndef SQLITE_OMIT_SHARED_CACHE
92/*
93** Enable or disable the shared pager and schema features.
94**
95** This routine has no effect on existing database connections.
96** The shared cache setting effects only future calls to
97** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
98*/
99int sqlite3_enable_shared_cache(int enable){
100 sqlite3GlobalConfig.sharedCacheEnabled = enable;
101 return SQLITE_OK;
102}
103#endif
104
105
106
107#ifdef SQLITE_OMIT_SHARED_CACHE
108 /*
109 ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
110 ** and clearAllSharedCacheTableLocks()
111 ** manipulate entries in the BtShared.pLock linked list used to store
112 ** shared-cache table level locks. If the library is compiled with the
113 ** shared-cache feature disabled, then there is only ever one user
114 ** of each BtShared structure and so this locking is not necessary.
115 ** So define the lock related functions as no-ops.
116 */
117 #define querySharedCacheTableLock(a,b,c) SQLITE_OK
118 #define setSharedCacheTableLock(a,b,c) SQLITE_OK
119 #define clearAllSharedCacheTableLocks(a)
120 #define downgradeAllSharedCacheTableLocks(a)
121 #define hasSharedCacheTableLock(a,b,c,d) 1
122 #define hasReadConflicts(a, b) 0
123#endif
124
125#ifdef SQLITE_DEBUG
126/*
127** Return and reset the seek counter for a Btree object.
128*/
129sqlite3_uint64 sqlite3BtreeSeekCount(Btree *pBt){
130 u64 n = pBt->nSeek;
131 pBt->nSeek = 0;
132 return n;
133}
134#endif
135
136/*
137** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
138** (MemPage*) as an argument. The (MemPage*) must not be NULL.
139**
140** If SQLITE_DEBUG is not defined, then this macro is equivalent to
141** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
142** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
143** with the page number and filename associated with the (MemPage*).
144*/
145#ifdef SQLITE_DEBUG
146int corruptPageError(int lineno, MemPage *p){
147 char *zMsg;
148 sqlite3BeginBenignMalloc();
149 zMsg = sqlite3_mprintf("database corruption page %u of %s",
150 p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
151 );
152 sqlite3EndBenignMalloc();
153 if( zMsg ){
154 sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
155 }
156 sqlite3_free(zMsg);
157 return SQLITE_CORRUPT_BKPT;
158}
159# define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
160#else
161# define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
162#endif
163
164/* Default value for SHARED_LOCK_TRACE macro if shared-cache is disabled
165** or if the lock tracking is disabled. This is always the value for
166** release builds.
167*/
168#define SHARED_LOCK_TRACE(X,MSG,TAB,TYPE) /*no-op*/
169
170#ifndef SQLITE_OMIT_SHARED_CACHE
171
172#if 0
173/* ^---- Change to 1 and recompile to enable shared-lock tracing
174** for debugging purposes.
175**
176** Print all shared-cache locks on a BtShared. Debugging use only.
177*/
178static void sharedLockTrace(
179 BtShared *pBt,
180 const char *zMsg,
181 int iRoot,
182 int eLockType
183){
184 BtLock *pLock;
185 if( iRoot>0 ){
186 printf("%s-%p %u%s:", zMsg, pBt, iRoot, eLockType==READ_LOCK?"R":"W");
187 }else{
188 printf("%s-%p:", zMsg, pBt);
189 }
190 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
191 printf(" %p/%u%s", pLock->pBtree, pLock->iTable,
192 pLock->eLock==READ_LOCK ? "R" : "W");
193 while( pLock->pNext && pLock->pBtree==pLock->pNext->pBtree ){
194 pLock = pLock->pNext;
195 printf(",%u%s", pLock->iTable, pLock->eLock==READ_LOCK ? "R" : "W");
196 }
197 }
198 printf("\n");
199 fflush(stdout);
200}
201#undef SHARED_LOCK_TRACE
202#define SHARED_LOCK_TRACE(X,MSG,TAB,TYPE) sharedLockTrace(X,MSG,TAB,TYPE)
203#endif /* Shared-lock tracing */
204
205#ifdef SQLITE_DEBUG
206/*
207**** This function is only used as part of an assert() statement. ***
208**
209** Check to see if pBtree holds the required locks to read or write to the
210** table with root page iRoot. Return 1 if it does and 0 if not.
211**
212** For example, when writing to a table with root-page iRoot via
213** Btree connection pBtree:
214**
215** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
216**
217** When writing to an index that resides in a sharable database, the
218** caller should have first obtained a lock specifying the root page of
219** the corresponding table. This makes things a bit more complicated,
220** as this module treats each table as a separate structure. To determine
221** the table corresponding to the index being written, this
222** function has to search through the database schema.
223**
224** Instead of a lock on the table/index rooted at page iRoot, the caller may
225** hold a write-lock on the schema table (root page 1). This is also
226** acceptable.
227*/
228static int hasSharedCacheTableLock(
229 Btree *pBtree, /* Handle that must hold lock */
230 Pgno iRoot, /* Root page of b-tree */
231 int isIndex, /* True if iRoot is the root of an index b-tree */
232 int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
233){
234 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
235 Pgno iTab = 0;
236 BtLock *pLock;
237
238 /* If this database is not shareable, or if the client is reading
239 ** and has the read-uncommitted flag set, then no lock is required.
240 ** Return true immediately.
241 */
242 if( (pBtree->sharable==0)
243 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
244 ){
245 return 1;
246 }
247
248 /* If the client is reading or writing an index and the schema is
249 ** not loaded, then it is too difficult to actually check to see if
250 ** the correct locks are held. So do not bother - just return true.
251 ** This case does not come up very often anyhow.
252 */
253 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
254 return 1;
255 }
256
257 /* Figure out the root-page that the lock should be held on. For table
258 ** b-trees, this is just the root page of the b-tree being read or
259 ** written. For index b-trees, it is the root page of the associated
260 ** table. */
261 if( isIndex ){
262 HashElem *p;
263 int bSeen = 0;
264 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
265 Index *pIdx = (Index *)sqliteHashData(p);
266 if( pIdx->tnum==iRoot ){
267 if( bSeen ){
268 /* Two or more indexes share the same root page. There must
269 ** be imposter tables. So just return true. The assert is not
270 ** useful in that case. */
271 return 1;
272 }
273 iTab = pIdx->pTable->tnum;
274 bSeen = 1;
275 }
276 }
277 }else{
278 iTab = iRoot;
279 }
280
281 SHARED_LOCK_TRACE(pBtree->pBt,"hasLock",iRoot,eLockType);
282
283 /* Search for the required lock. Either a write-lock on root-page iTab, a
284 ** write-lock on the schema table, or (if the client is reading) a
285 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
286 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
287 if( pLock->pBtree==pBtree
288 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
289 && pLock->eLock>=eLockType
290 ){
291 return 1;
292 }
293 }
294
295 /* Failed to find the required lock. */
296 return 0;
297}
298#endif /* SQLITE_DEBUG */
299
300#ifdef SQLITE_DEBUG
301/*
302**** This function may be used as part of assert() statements only. ****
303**
304** Return true if it would be illegal for pBtree to write into the
305** table or index rooted at iRoot because other shared connections are
306** simultaneously reading that same table or index.
307**
308** It is illegal for pBtree to write if some other Btree object that
309** shares the same BtShared object is currently reading or writing
310** the iRoot table. Except, if the other Btree object has the
311** read-uncommitted flag set, then it is OK for the other object to
312** have a read cursor.
313**
314** For example, before writing to any part of the table or index
315** rooted at page iRoot, one should call:
316**
317** assert( !hasReadConflicts(pBtree, iRoot) );
318*/
319static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
320 BtCursor *p;
321 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
322 if( p->pgnoRoot==iRoot
323 && p->pBtree!=pBtree
324 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
325 ){
326 return 1;
327 }
328 }
329 return 0;
330}
331#endif /* #ifdef SQLITE_DEBUG */
332
333/*
334** Query to see if Btree handle p may obtain a lock of type eLock
335** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
336** SQLITE_OK if the lock may be obtained (by calling
337** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
338*/
339static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
340 BtShared *pBt = p->pBt;
341 BtLock *pIter;
342
343 assert( sqlite3BtreeHoldsMutex(p) );
344 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
345 assert( p->db!=0 );
346 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
347
348 /* If requesting a write-lock, then the Btree must have an open write
349 ** transaction on this file. And, obviously, for this to be so there
350 ** must be an open write transaction on the file itself.
351 */
352 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
353 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
354
355 /* This routine is a no-op if the shared-cache is not enabled */
356 if( !p->sharable ){
357 return SQLITE_OK;
358 }
359
360 /* If some other connection is holding an exclusive lock, the
361 ** requested lock may not be obtained.
362 */
363 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
364 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
365 return SQLITE_LOCKED_SHAREDCACHE;
366 }
367
368 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
369 /* The condition (pIter->eLock!=eLock) in the following if(...)
370 ** statement is a simplification of:
371 **
372 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
373 **
374 ** since we know that if eLock==WRITE_LOCK, then no other connection
375 ** may hold a WRITE_LOCK on any table in this file (since there can
376 ** only be a single writer).
377 */
378 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
379 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
380 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
381 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
382 if( eLock==WRITE_LOCK ){
383 assert( p==pBt->pWriter );
384 pBt->btsFlags |= BTS_PENDING;
385 }
386 return SQLITE_LOCKED_SHAREDCACHE;
387 }
388 }
389 return SQLITE_OK;
390}
391#endif /* !SQLITE_OMIT_SHARED_CACHE */
392
393#ifndef SQLITE_OMIT_SHARED_CACHE
394/*
395** Add a lock on the table with root-page iTable to the shared-btree used
396** by Btree handle p. Parameter eLock must be either READ_LOCK or
397** WRITE_LOCK.
398**
399** This function assumes the following:
400**
401** (a) The specified Btree object p is connected to a sharable
402** database (one with the BtShared.sharable flag set), and
403**
404** (b) No other Btree objects hold a lock that conflicts
405** with the requested lock (i.e. querySharedCacheTableLock() has
406** already been called and returned SQLITE_OK).
407**
408** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
409** is returned if a malloc attempt fails.
410*/
411static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
412 BtShared *pBt = p->pBt;
413 BtLock *pLock = 0;
414 BtLock *pIter;
415
416 SHARED_LOCK_TRACE(pBt,"setLock", iTable, eLock);
417
418 assert( sqlite3BtreeHoldsMutex(p) );
419 assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
420 assert( p->db!=0 );
421
422 /* A connection with the read-uncommitted flag set will never try to
423 ** obtain a read-lock using this function. The only read-lock obtained
424 ** by a connection in read-uncommitted mode is on the sqlite_schema
425 ** table, and that lock is obtained in BtreeBeginTrans(). */
426 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
427
428 /* This function should only be called on a sharable b-tree after it
429 ** has been determined that no other b-tree holds a conflicting lock. */
430 assert( p->sharable );
431 assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
432
433 /* First search the list for an existing lock on this table. */
434 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
435 if( pIter->iTable==iTable && pIter->pBtree==p ){
436 pLock = pIter;
437 break;
438 }
439 }
440
441 /* If the above search did not find a BtLock struct associating Btree p
442 ** with table iTable, allocate one and link it into the list.
443 */
444 if( !pLock ){
445 pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
446 if( !pLock ){
447 return SQLITE_NOMEM_BKPT;
448 }
449 pLock->iTable = iTable;
450 pLock->pBtree = p;
451 pLock->pNext = pBt->pLock;
452 pBt->pLock = pLock;
453 }
454
455 /* Set the BtLock.eLock variable to the maximum of the current lock
456 ** and the requested lock. This means if a write-lock was already held
457 ** and a read-lock requested, we don't incorrectly downgrade the lock.
458 */
459 assert( WRITE_LOCK>READ_LOCK );
460 if( eLock>pLock->eLock ){
461 pLock->eLock = eLock;
462 }
463
464 return SQLITE_OK;
465}
466#endif /* !SQLITE_OMIT_SHARED_CACHE */
467
468#ifndef SQLITE_OMIT_SHARED_CACHE
469/*
470** Release all the table locks (locks obtained via calls to
471** the setSharedCacheTableLock() procedure) held by Btree object p.
472**
473** This function assumes that Btree p has an open read or write
474** transaction. If it does not, then the BTS_PENDING flag
475** may be incorrectly cleared.
476*/
477static void clearAllSharedCacheTableLocks(Btree *p){
478 BtShared *pBt = p->pBt;
479 BtLock **ppIter = &pBt->pLock;
480
481 assert( sqlite3BtreeHoldsMutex(p) );
482 assert( p->sharable || 0==*ppIter );
483 assert( p->inTrans>0 );
484
485 SHARED_LOCK_TRACE(pBt, "clearAllLocks", 0, 0);
486
487 while( *ppIter ){
488 BtLock *pLock = *ppIter;
489 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
490 assert( pLock->pBtree->inTrans>=pLock->eLock );
491 if( pLock->pBtree==p ){
492 *ppIter = pLock->pNext;
493 assert( pLock->iTable!=1 || pLock==&p->lock );
494 if( pLock->iTable!=1 ){
495 sqlite3_free(pLock);
496 }
497 }else{
498 ppIter = &pLock->pNext;
499 }
500 }
501
502 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
503 if( pBt->pWriter==p ){
504 pBt->pWriter = 0;
505 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
506 }else if( pBt->nTransaction==2 ){
507 /* This function is called when Btree p is concluding its
508 ** transaction. If there currently exists a writer, and p is not
509 ** that writer, then the number of locks held by connections other
510 ** than the writer must be about to drop to zero. In this case
511 ** set the BTS_PENDING flag to 0.
512 **
513 ** If there is not currently a writer, then BTS_PENDING must
514 ** be zero already. So this next line is harmless in that case.
515 */
516 pBt->btsFlags &= ~BTS_PENDING;
517 }
518}
519
520/*
521** This function changes all write-locks held by Btree p into read-locks.
522*/
523static void downgradeAllSharedCacheTableLocks(Btree *p){
524 BtShared *pBt = p->pBt;
525
526 SHARED_LOCK_TRACE(pBt, "downgradeLocks", 0, 0);
527
528 if( pBt->pWriter==p ){
529 BtLock *pLock;
530 pBt->pWriter = 0;
531 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
532 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
533 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
534 pLock->eLock = READ_LOCK;
535 }
536 }
537}
538
539#endif /* SQLITE_OMIT_SHARED_CACHE */
540
541static void releasePage(MemPage *pPage); /* Forward reference */
542static void releasePageOne(MemPage *pPage); /* Forward reference */
543static void releasePageNotNull(MemPage *pPage); /* Forward reference */
544
545/*
546***** This routine is used inside of assert() only ****
547**
548** Verify that the cursor holds the mutex on its BtShared
549*/
550#ifdef SQLITE_DEBUG
551static int cursorHoldsMutex(BtCursor *p){
552 return sqlite3_mutex_held(p->pBt->mutex);
553}
554
555/* Verify that the cursor and the BtShared agree about what is the current
556** database connetion. This is important in shared-cache mode. If the database
557** connection pointers get out-of-sync, it is possible for routines like
558** btreeInitPage() to reference an stale connection pointer that references a
559** a connection that has already closed. This routine is used inside assert()
560** statements only and for the purpose of double-checking that the btree code
561** does keep the database connection pointers up-to-date.
562*/
563static int cursorOwnsBtShared(BtCursor *p){
564 assert( cursorHoldsMutex(p) );
565 return (p->pBtree->db==p->pBt->db);
566}
567#endif
568
569/*
570** Invalidate the overflow cache of the cursor passed as the first argument.
571** on the shared btree structure pBt.
572*/
573#define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
574
575/*
576** Invalidate the overflow page-list cache for all cursors opened
577** on the shared btree structure pBt.
578*/
579static void invalidateAllOverflowCache(BtShared *pBt){
580 BtCursor *p;
581 assert( sqlite3_mutex_held(pBt->mutex) );
582 for(p=pBt->pCursor; p; p=p->pNext){
583 invalidateOverflowCache(p);
584 }
585}
586
587#ifndef SQLITE_OMIT_INCRBLOB
588/*
589** This function is called before modifying the contents of a table
590** to invalidate any incrblob cursors that are open on the
591** row or one of the rows being modified.
592**
593** If argument isClearTable is true, then the entire contents of the
594** table is about to be deleted. In this case invalidate all incrblob
595** cursors open on any row within the table with root-page pgnoRoot.
596**
597** Otherwise, if argument isClearTable is false, then the row with
598** rowid iRow is being replaced or deleted. In this case invalidate
599** only those incrblob cursors open on that specific row.
600*/
601static void invalidateIncrblobCursors(
602 Btree *pBtree, /* The database file to check */
603 Pgno pgnoRoot, /* The table that might be changing */
604 i64 iRow, /* The rowid that might be changing */
605 int isClearTable /* True if all rows are being deleted */
606){
607 BtCursor *p;
608 assert( pBtree->hasIncrblobCur );
609 assert( sqlite3BtreeHoldsMutex(pBtree) );
610 pBtree->hasIncrblobCur = 0;
611 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
612 if( (p->curFlags & BTCF_Incrblob)!=0 ){
613 pBtree->hasIncrblobCur = 1;
614 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
615 p->eState = CURSOR_INVALID;
616 }
617 }
618 }
619}
620
621#else
622 /* Stub function when INCRBLOB is omitted */
623 #define invalidateIncrblobCursors(w,x,y,z)
624#endif /* SQLITE_OMIT_INCRBLOB */
625
626/*
627** Set bit pgno of the BtShared.pHasContent bitvec. This is called
628** when a page that previously contained data becomes a free-list leaf
629** page.
630**
631** The BtShared.pHasContent bitvec exists to work around an obscure
632** bug caused by the interaction of two useful IO optimizations surrounding
633** free-list leaf pages:
634**
635** 1) When all data is deleted from a page and the page becomes
636** a free-list leaf page, the page is not written to the database
637** (as free-list leaf pages contain no meaningful data). Sometimes
638** such a page is not even journalled (as it will not be modified,
639** why bother journalling it?).
640**
641** 2) When a free-list leaf page is reused, its content is not read
642** from the database or written to the journal file (why should it
643** be, if it is not at all meaningful?).
644**
645** By themselves, these optimizations work fine and provide a handy
646** performance boost to bulk delete or insert operations. However, if
647** a page is moved to the free-list and then reused within the same
648** transaction, a problem comes up. If the page is not journalled when
649** it is moved to the free-list and it is also not journalled when it
650** is extracted from the free-list and reused, then the original data
651** may be lost. In the event of a rollback, it may not be possible
652** to restore the database to its original configuration.
653**
654** The solution is the BtShared.pHasContent bitvec. Whenever a page is
655** moved to become a free-list leaf page, the corresponding bit is
656** set in the bitvec. Whenever a leaf page is extracted from the free-list,
657** optimization 2 above is omitted if the corresponding bit is already
658** set in BtShared.pHasContent. The contents of the bitvec are cleared
659** at the end of every transaction.
660*/
661static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
662 int rc = SQLITE_OK;
663 if( !pBt->pHasContent ){
664 assert( pgno<=pBt->nPage );
665 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
666 if( !pBt->pHasContent ){
667 rc = SQLITE_NOMEM_BKPT;
668 }
669 }
670 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
671 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
672 }
673 return rc;
674}
675
676/*
677** Query the BtShared.pHasContent vector.
678**
679** This function is called when a free-list leaf page is removed from the
680** free-list for reuse. It returns false if it is safe to retrieve the
681** page from the pager layer with the 'no-content' flag set. True otherwise.
682*/
683static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
684 Bitvec *p = pBt->pHasContent;
685 return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
686}
687
688/*
689** Clear (destroy) the BtShared.pHasContent bitvec. This should be
690** invoked at the conclusion of each write-transaction.
691*/
692static void btreeClearHasContent(BtShared *pBt){
693 sqlite3BitvecDestroy(pBt->pHasContent);
694 pBt->pHasContent = 0;
695}
696
697/*
698** Release all of the apPage[] pages for a cursor.
699*/
700static void btreeReleaseAllCursorPages(BtCursor *pCur){
701 int i;
702 if( pCur->iPage>=0 ){
703 for(i=0; i<pCur->iPage; i++){
704 releasePageNotNull(pCur->apPage[i]);
705 }
706 releasePageNotNull(pCur->pPage);
707 pCur->iPage = -1;
708 }
709}
710
711/*
712** The cursor passed as the only argument must point to a valid entry
713** when this function is called (i.e. have eState==CURSOR_VALID). This
714** function saves the current cursor key in variables pCur->nKey and
715** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
716** code otherwise.
717**
718** If the cursor is open on an intkey table, then the integer key
719** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
720** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
721** set to point to a malloced buffer pCur->nKey bytes in size containing
722** the key.
723*/
724static int saveCursorKey(BtCursor *pCur){
725 int rc = SQLITE_OK;
726 assert( CURSOR_VALID==pCur->eState );
727 assert( 0==pCur->pKey );
728 assert( cursorHoldsMutex(pCur) );
729
730 if( pCur->curIntKey ){
731 /* Only the rowid is required for a table btree */
732 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
733 }else{
734 /* For an index btree, save the complete key content. It is possible
735 ** that the current key is corrupt. In that case, it is possible that
736 ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
737 ** up to the size of 1 varint plus 1 8-byte value when the cursor
738 ** position is restored. Hence the 17 bytes of padding allocated
739 ** below. */
740 void *pKey;
741 pCur->nKey = sqlite3BtreePayloadSize(pCur);
742 pKey = sqlite3Malloc( ((i64)pCur->nKey) + 9 + 8 );
743 if( pKey ){
744 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
745 if( rc==SQLITE_OK ){
746 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
747 pCur->pKey = pKey;
748 }else{
749 sqlite3_free(pKey);
750 }
751 }else{
752 rc = SQLITE_NOMEM_BKPT;
753 }
754 }
755 assert( !pCur->curIntKey || !pCur->pKey );
756 return rc;
757}
758
759/*
760** Save the current cursor position in the variables BtCursor.nKey
761** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
762**
763** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
764** prior to calling this routine.
765*/
766static int saveCursorPosition(BtCursor *pCur){
767 int rc;
768
769 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
770 assert( 0==pCur->pKey );
771 assert( cursorHoldsMutex(pCur) );
772
773 if( pCur->curFlags & BTCF_Pinned ){
774 return SQLITE_CONSTRAINT_PINNED;
775 }
776 if( pCur->eState==CURSOR_SKIPNEXT ){
777 pCur->eState = CURSOR_VALID;
778 }else{
779 pCur->skipNext = 0;
780 }
781
782 rc = saveCursorKey(pCur);
783 if( rc==SQLITE_OK ){
784 btreeReleaseAllCursorPages(pCur);
785 pCur->eState = CURSOR_REQUIRESEEK;
786 }
787
788 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
789 return rc;
790}
791
792/* Forward reference */
793static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
794
795/*
796** Save the positions of all cursors (except pExcept) that are open on
797** the table with root-page iRoot. "Saving the cursor position" means that
798** the location in the btree is remembered in such a way that it can be
799** moved back to the same spot after the btree has been modified. This
800** routine is called just before cursor pExcept is used to modify the
801** table, for example in BtreeDelete() or BtreeInsert().
802**
803** If there are two or more cursors on the same btree, then all such
804** cursors should have their BTCF_Multiple flag set. The btreeCursor()
805** routine enforces that rule. This routine only needs to be called in
806** the uncommon case when pExpect has the BTCF_Multiple flag set.
807**
808** If pExpect!=NULL and if no other cursors are found on the same root-page,
809** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
810** pointless call to this routine.
811**
812** Implementation note: This routine merely checks to see if any cursors
813** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
814** event that cursors are in need to being saved.
815*/
816static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
817 BtCursor *p;
818 assert( sqlite3_mutex_held(pBt->mutex) );
819 assert( pExcept==0 || pExcept->pBt==pBt );
820 for(p=pBt->pCursor; p; p=p->pNext){
821 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
822 }
823 if( p ) return saveCursorsOnList(p, iRoot, pExcept);
824 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
825 return SQLITE_OK;
826}
827
828/* This helper routine to saveAllCursors does the actual work of saving
829** the cursors if and when a cursor is found that actually requires saving.
830** The common case is that no cursors need to be saved, so this routine is
831** broken out from its caller to avoid unnecessary stack pointer movement.
832*/
833static int SQLITE_NOINLINE saveCursorsOnList(
834 BtCursor *p, /* The first cursor that needs saving */
835 Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
836 BtCursor *pExcept /* Do not save this cursor */
837){
838 do{
839 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
840 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
841 int rc = saveCursorPosition(p);
842 if( SQLITE_OK!=rc ){
843 return rc;
844 }
845 }else{
846 testcase( p->iPage>=0 );
847 btreeReleaseAllCursorPages(p);
848 }
849 }
850 p = p->pNext;
851 }while( p );
852 return SQLITE_OK;
853}
854
855/*
856** Clear the current cursor position.
857*/
858void sqlite3BtreeClearCursor(BtCursor *pCur){
859 assert( cursorHoldsMutex(pCur) );
860 sqlite3_free(pCur->pKey);
861 pCur->pKey = 0;
862 pCur->eState = CURSOR_INVALID;
863}
864
865/*
866** In this version of BtreeMoveto, pKey is a packed index record
867** such as is generated by the OP_MakeRecord opcode. Unpack the
868** record and then call sqlite3BtreeIndexMoveto() to do the work.
869*/
870static int btreeMoveto(
871 BtCursor *pCur, /* Cursor open on the btree to be searched */
872 const void *pKey, /* Packed key if the btree is an index */
873 i64 nKey, /* Integer key for tables. Size of pKey for indices */
874 int bias, /* Bias search to the high end */
875 int *pRes /* Write search results here */
876){
877 int rc; /* Status code */
878 UnpackedRecord *pIdxKey; /* Unpacked index key */
879
880 if( pKey ){
881 KeyInfo *pKeyInfo = pCur->pKeyInfo;
882 assert( nKey==(i64)(int)nKey );
883 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
884 if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
885 sqlite3VdbeRecordUnpack((int)nKey, pKey, pIdxKey);
886 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
887 rc = SQLITE_CORRUPT_BKPT;
888 }else{
889 rc = sqlite3BtreeIndexMoveto(pCur, pIdxKey, pRes);
890 }
891 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
892 }else{
893 pIdxKey = 0;
894 rc = sqlite3BtreeTableMoveto(pCur, nKey, bias, pRes);
895 }
896 return rc;
897}
898
899/*
900** Restore the cursor to the position it was in (or as close to as possible)
901** when saveCursorPosition() was called. Note that this call deletes the
902** saved position info stored by saveCursorPosition(), so there can be
903** at most one effective restoreCursorPosition() call after each
904** saveCursorPosition().
905*/
906static int btreeRestoreCursorPosition(BtCursor *pCur){
907 int rc;
908 int skipNext = 0;
909 assert( cursorOwnsBtShared(pCur) );
910 assert( pCur->eState>=CURSOR_REQUIRESEEK );
911 if( pCur->eState==CURSOR_FAULT ){
912 return pCur->skipNext;
913 }
914 pCur->eState = CURSOR_INVALID;
915 if( sqlite3FaultSim(410) ){
916 rc = SQLITE_IOERR;
917 }else{
918 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
919 }
920 if( rc==SQLITE_OK ){
921 sqlite3_free(pCur->pKey);
922 pCur->pKey = 0;
923 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
924 if( skipNext ) pCur->skipNext = skipNext;
925 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
926 pCur->eState = CURSOR_SKIPNEXT;
927 }
928 }
929 return rc;
930}
931
932#define restoreCursorPosition(p) \
933 (p->eState>=CURSOR_REQUIRESEEK ? \
934 btreeRestoreCursorPosition(p) : \
935 SQLITE_OK)
936
937/*
938** Determine whether or not a cursor has moved from the position where
939** it was last placed, or has been invalidated for any other reason.
940** Cursors can move when the row they are pointing at is deleted out
941** from under them, for example. Cursor might also move if a btree
942** is rebalanced.
943**
944** Calling this routine with a NULL cursor pointer returns false.
945**
946** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
947** back to where it ought to be if this routine returns true.
948*/
949int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
950 assert( EIGHT_BYTE_ALIGNMENT(pCur)
951 || pCur==sqlite3BtreeFakeValidCursor() );
952 assert( offsetof(BtCursor, eState)==0 );
953 assert( sizeof(pCur->eState)==1 );
954 return CURSOR_VALID != *(u8*)pCur;
955}
956
957/*
958** Return a pointer to a fake BtCursor object that will always answer
959** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
960** cursor returned must not be used with any other Btree interface.
961*/
962BtCursor *sqlite3BtreeFakeValidCursor(void){
963 static u8 fakeCursor = CURSOR_VALID;
964 assert( offsetof(BtCursor, eState)==0 );
965 return (BtCursor*)&fakeCursor;
966}
967
968/*
969** This routine restores a cursor back to its original position after it
970** has been moved by some outside activity (such as a btree rebalance or
971** a row having been deleted out from under the cursor).
972**
973** On success, the *pDifferentRow parameter is false if the cursor is left
974** pointing at exactly the same row. *pDifferntRow is the row the cursor
975** was pointing to has been deleted, forcing the cursor to point to some
976** nearby row.
977**
978** This routine should only be called for a cursor that just returned
979** TRUE from sqlite3BtreeCursorHasMoved().
980*/
981int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
982 int rc;
983
984 assert( pCur!=0 );
985 assert( pCur->eState!=CURSOR_VALID );
986 rc = restoreCursorPosition(pCur);
987 if( rc ){
988 *pDifferentRow = 1;
989 return rc;
990 }
991 if( pCur->eState!=CURSOR_VALID ){
992 *pDifferentRow = 1;
993 }else{
994 *pDifferentRow = 0;
995 }
996 return SQLITE_OK;
997}
998
999#ifdef SQLITE_ENABLE_CURSOR_HINTS
1000/*
1001** Provide hints to the cursor. The particular hint given (and the type
1002** and number of the varargs parameters) is determined by the eHintType
1003** parameter. See the definitions of the BTREE_HINT_* macros for details.
1004*/
1005void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
1006 /* Used only by system that substitute their own storage engine */
1007#ifdef SQLITE_DEBUG
1008 va_list ap;
1009 va_start(ap, eHintType);
1010 if( eHintType==BTREE_HINT_RANGE ){
1011 Expr *pExpr;
1012 Walker w;
1013 memset(&w, 0, sizeof(w));
1014 w.xExprCallback = sqlite3CursorRangeHintExprCheck;
1015 pExpr = va_arg(ap, Expr*);
1016 w.u.aMem = va_arg(ap, Mem*);
1017 assert( pExpr!=0 );
1018 assert( w.u.aMem!=0 );
1019 sqlite3WalkExpr(&w, pExpr);
1020 }else if( ALWAYS(eHintType==BTREE_HINT_TABLECURSOR) ){
1021 BtCursor *pCsr = va_arg(ap, BtCursor*);
1022 assert( pCur->pCursorHintTableCursor==0
1023 || pCur->pCursorHintTableCursor==pCsr
1024 );
1025 assert( pCsr->pKeyInfo==0 || CORRUPT_DB );
1026 pCur->pCursorHintTableCursor = pCsr;
1027 }
1028 va_end(ap);
1029#endif /* SQLITE_DEBUG */
1030}
1031#endif /* SQLITE_ENABLE_CURSOR_HINTS */
1032
1033#if defined(SQLITE_ENABLE_CURSOR_HINTS) && defined(SQLITE_DEBUG)
1034/*
1035** Return the pointer configured via the BTREE_HINT_TABLECURSOR hint on
1036** cursor pCsr. This is used from OP_DeferredSeek to assert() that the
1037** index cursor has been correctly configured with the table cursor.
1038*/
1039BtCursor *sqlite3BtreeCursorHintTblCsr(BtCursor *pCsr){
1040 return pCsr->pCursorHintTableCursor;
1041}
1042#endif
1043
1044/*
1045** Provide flag hints to the cursor.
1046*/
1047void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
1048 assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
1049 pCur->hints = (u8)x;
1050}
1051
1052
1053#ifndef SQLITE_OMIT_AUTOVACUUM
1054/*
1055** Given a page number of a regular database page, return the page
1056** number for the pointer-map page that contains the entry for the
1057** input page number.
1058**
1059** Return 0 (not a valid page) for pgno==1 since there is
1060** no pointer map associated with page 1. The integrity_check logic
1061** requires that ptrmapPageno(*,1)!=1.
1062*/
1063static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
1064 int nPagesPerMapPage;
1065 Pgno iPtrMap, ret;
1066 assert( sqlite3_mutex_held(pBt->mutex) );
1067 if( pgno<2 ) return 0;
1068 nPagesPerMapPage = (pBt->usableSize/5)+1;
1069 iPtrMap = (pgno-2)/nPagesPerMapPage;
1070 ret = (iPtrMap*nPagesPerMapPage) + 2;
1071 if( ret==PENDING_BYTE_PAGE(pBt) ){
1072 ret++;
1073 }
1074 return ret;
1075}
1076
1077/*
1078** Write an entry into the pointer map.
1079**
1080** This routine updates the pointer map entry for page number 'key'
1081** so that it maps to type 'eType' and parent page number 'pgno'.
1082**
1083** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
1084** a no-op. If an error occurs, the appropriate error code is written
1085** into *pRC.
1086*/
1087static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
1088 DbPage *pDbPage; /* The pointer map page */
1089 u8 *pPtrmap; /* The pointer map data */
1090 Pgno iPtrmap; /* The pointer map page number */
1091 int offset; /* Offset in pointer map page */
1092 int rc; /* Return code from subfunctions */
1093
1094 if( *pRC ) return;
1095
1096 assert( sqlite3_mutex_held(pBt->mutex) );
1097 /* The super-journal page number must never be used as a pointer map page */
1098 assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
1099
1100 assert( pBt->autoVacuum );
1101 if( key==0 ){
1102 *pRC = SQLITE_CORRUPT_BKPT;
1103 return;
1104 }
1105 iPtrmap = PTRMAP_PAGENO(pBt, key);
1106 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1107 if( rc!=SQLITE_OK ){
1108 *pRC = rc;
1109 return;
1110 }
1111 if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
1112 /* The first byte of the extra data is the MemPage.isInit byte.
1113 ** If that byte is set, it means this page is also being used
1114 ** as a btree page. */
1115 *pRC = SQLITE_CORRUPT_BKPT;
1116 goto ptrmap_exit;
1117 }
1118 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1119 if( offset<0 ){
1120 *pRC = SQLITE_CORRUPT_BKPT;
1121 goto ptrmap_exit;
1122 }
1123 assert( offset <= (int)pBt->usableSize-5 );
1124 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1125
1126 if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
1127 TRACE(("PTRMAP_UPDATE: %u->(%u,%u)\n", key, eType, parent));
1128 *pRC= rc = sqlite3PagerWrite(pDbPage);
1129 if( rc==SQLITE_OK ){
1130 pPtrmap[offset] = eType;
1131 put4byte(&pPtrmap[offset+1], parent);
1132 }
1133 }
1134
1135ptrmap_exit:
1136 sqlite3PagerUnref(pDbPage);
1137}
1138
1139/*
1140** Read an entry from the pointer map.
1141**
1142** This routine retrieves the pointer map entry for page 'key', writing
1143** the type and parent page number to *pEType and *pPgno respectively.
1144** An error code is returned if something goes wrong, otherwise SQLITE_OK.
1145*/
1146static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
1147 DbPage *pDbPage; /* The pointer map page */
1148 int iPtrmap; /* Pointer map page index */
1149 u8 *pPtrmap; /* Pointer map page data */
1150 int offset; /* Offset of entry in pointer map */
1151 int rc;
1152
1153 assert( sqlite3_mutex_held(pBt->mutex) );
1154
1155 iPtrmap = PTRMAP_PAGENO(pBt, key);
1156 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
1157 if( rc!=0 ){
1158 return rc;
1159 }
1160 pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
1161
1162 offset = PTRMAP_PTROFFSET(iPtrmap, key);
1163 if( offset<0 ){
1164 sqlite3PagerUnref(pDbPage);
1165 return SQLITE_CORRUPT_BKPT;
1166 }
1167 assert( offset <= (int)pBt->usableSize-5 );
1168 assert( pEType!=0 );
1169 *pEType = pPtrmap[offset];
1170 if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
1171
1172 sqlite3PagerUnref(pDbPage);
1173 if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
1174 return SQLITE_OK;
1175}
1176
1177#else /* if defined SQLITE_OMIT_AUTOVACUUM */
1178 #define ptrmapPut(w,x,y,z,rc)
1179 #define ptrmapGet(w,x,y,z) SQLITE_OK
1180 #define ptrmapPutOvflPtr(x, y, z, rc)
1181#endif
1182
1183/*
1184** Given a btree page and a cell index (0 means the first cell on
1185** the page, 1 means the second cell, and so forth) return a pointer
1186** to the cell content.
1187**
1188** findCellPastPtr() does the same except it skips past the initial
1189** 4-byte child pointer found on interior pages, if there is one.
1190**
1191** This routine works only for pages that do not contain overflow cells.
1192*/
1193#define findCell(P,I) \
1194 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1195#define findCellPastPtr(P,I) \
1196 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
1197
1198
1199/*
1200** This is common tail processing for btreeParseCellPtr() and
1201** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
1202** on a single B-tree page. Make necessary adjustments to the CellInfo
1203** structure.
1204*/
1205static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
1206 MemPage *pPage, /* Page containing the cell */
1207 u8 *pCell, /* Pointer to the cell text. */
1208 CellInfo *pInfo /* Fill in this structure */
1209){
1210 /* If the payload will not fit completely on the local page, we have
1211 ** to decide how much to store locally and how much to spill onto
1212 ** overflow pages. The strategy is to minimize the amount of unused
1213 ** space on overflow pages while keeping the amount of local storage
1214 ** in between minLocal and maxLocal.
1215 **
1216 ** Warning: changing the way overflow payload is distributed in any
1217 ** way will result in an incompatible file format.
1218 */
1219 int minLocal; /* Minimum amount of payload held locally */
1220 int maxLocal; /* Maximum amount of payload held locally */
1221 int surplus; /* Overflow payload available for local storage */
1222
1223 minLocal = pPage->minLocal;
1224 maxLocal = pPage->maxLocal;
1225 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
1226 testcase( surplus==maxLocal );
1227 testcase( surplus==maxLocal+1 );
1228 if( surplus <= maxLocal ){
1229 pInfo->nLocal = (u16)surplus;
1230 }else{
1231 pInfo->nLocal = (u16)minLocal;
1232 }
1233 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
1234}
1235
1236/*
1237** Given a record with nPayload bytes of payload stored within btree
1238** page pPage, return the number of bytes of payload stored locally.
1239*/
1240static int btreePayloadToLocal(MemPage *pPage, i64 nPayload){
1241 int maxLocal; /* Maximum amount of payload held locally */
1242 maxLocal = pPage->maxLocal;
1243 assert( nPayload>=0 );
1244 if( nPayload<=maxLocal ){
1245 return (int)nPayload;
1246 }else{
1247 int minLocal; /* Minimum amount of payload held locally */
1248 int surplus; /* Overflow payload available for local storage */
1249 minLocal = pPage->minLocal;
1250 surplus = (int)(minLocal +(nPayload - minLocal)%(pPage->pBt->usableSize-4));
1251 return (surplus <= maxLocal) ? surplus : minLocal;
1252 }
1253}
1254
1255/*
1256** The following routines are implementations of the MemPage.xParseCell()
1257** method.
1258**
1259** Parse a cell content block and fill in the CellInfo structure.
1260**
1261** btreeParseCellPtr() => table btree leaf nodes
1262** btreeParseCellNoPayload() => table btree internal nodes
1263** btreeParseCellPtrIndex() => index btree nodes
1264**
1265** There is also a wrapper function btreeParseCell() that works for
1266** all MemPage types and that references the cell by index rather than
1267** by pointer.
1268*/
1269static void btreeParseCellPtrNoPayload(
1270 MemPage *pPage, /* Page containing the cell */
1271 u8 *pCell, /* Pointer to the cell text. */
1272 CellInfo *pInfo /* Fill in this structure */
1273){
1274 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1275 assert( pPage->leaf==0 );
1276 assert( pPage->childPtrSize==4 );
1277#ifndef SQLITE_DEBUG
1278 UNUSED_PARAMETER(pPage);
1279#endif
1280 pInfo->nSize = 4 + sqlite3GetVarint(&pCell[4], (u64*)&pInfo->nKey);
1281 pInfo->nPayload = 0;
1282 pInfo->nLocal = 0;
1283 pInfo->pPayload = 0;
1284 return;
1285}
1286static void btreeParseCellPtr(
1287 MemPage *pPage, /* Page containing the cell */
1288 u8 *pCell, /* Pointer to the cell text. */
1289 CellInfo *pInfo /* Fill in this structure */
1290){
1291 u8 *pIter; /* For scanning through pCell */
1292 u64 nPayload; /* Number of bytes of cell payload */
1293 u64 iKey; /* Extracted Key value */
1294
1295 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1296 assert( pPage->leaf==0 || pPage->leaf==1 );
1297 assert( pPage->intKeyLeaf );
1298 assert( pPage->childPtrSize==0 );
1299 pIter = pCell;
1300
1301 /* The next block of code is equivalent to:
1302 **
1303 ** pIter += getVarint32(pIter, nPayload);
1304 **
1305 ** The code is inlined to avoid a function call.
1306 */
1307 nPayload = *pIter;
1308 if( nPayload>=0x80 ){
1309 u8 *pEnd = &pIter[8];
1310 nPayload &= 0x7f;
1311 do{
1312 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1313 }while( (*pIter)>=0x80 && pIter<pEnd );
1314 nPayload &= 0xffffffff;
1315 }
1316 pIter++;
1317
1318 /* The next block of code is equivalent to:
1319 **
1320 ** pIter += sqlite3GetVarint(pIter, (u64*)&pInfo->nKey);
1321 **
1322 ** The code is inlined and the loop is unrolled for performance.
1323 ** This routine is a high-runner.
1324 */
1325 iKey = *pIter;
1326 if( iKey>=0x80 ){
1327 u8 x;
1328 iKey = (iKey<<7) ^ (x = *++pIter);
1329 if( x>=0x80 ){
1330 iKey = (iKey<<7) ^ (x = *++pIter);
1331 if( x>=0x80 ){
1332 iKey = (iKey<<7) ^ 0x10204000 ^ (x = *++pIter);
1333 if( x>=0x80 ){
1334 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1335 if( x>=0x80 ){
1336 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1337 if( x>=0x80 ){
1338 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1339 if( x>=0x80 ){
1340 iKey = (iKey<<7) ^ 0x4000 ^ (x = *++pIter);
1341 if( x>=0x80 ){
1342 iKey = (iKey<<8) ^ 0x8000 ^ (*++pIter);
1343 }
1344 }
1345 }
1346 }
1347 }
1348 }else{
1349 iKey ^= 0x204000;
1350 }
1351 }else{
1352 iKey ^= 0x4000;
1353 }
1354 }
1355 pIter++;
1356
1357 pInfo->nKey = *(i64*)&iKey;
1358 pInfo->nPayload = (u32)nPayload;
1359 pInfo->pPayload = pIter;
1360 testcase( nPayload==pPage->maxLocal );
1361 testcase( nPayload==(u32)pPage->maxLocal+1 );
1362 assert( pPage->maxLocal <= BT_MAX_LOCAL );
1363 if( nPayload<=pPage->maxLocal ){
1364 /* This is the (easy) common case where the entire payload fits
1365 ** on the local page. No overflow is required.
1366 */
1367 pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell);
1368 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1369 pInfo->nLocal = (u16)nPayload;
1370 }else{
1371 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1372 }
1373}
1374static void btreeParseCellPtrIndex(
1375 MemPage *pPage, /* Page containing the cell */
1376 u8 *pCell, /* Pointer to the cell text. */
1377 CellInfo *pInfo /* Fill in this structure */
1378){
1379 u8 *pIter; /* For scanning through pCell */
1380 u32 nPayload; /* Number of bytes of cell payload */
1381
1382 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1383 assert( pPage->leaf==0 || pPage->leaf==1 );
1384 assert( pPage->intKeyLeaf==0 );
1385 pIter = pCell + pPage->childPtrSize;
1386 nPayload = *pIter;
1387 if( nPayload>=0x80 ){
1388 u8 *pEnd = &pIter[8];
1389 nPayload &= 0x7f;
1390 do{
1391 nPayload = (nPayload<<7) | (*++pIter & 0x7f);
1392 }while( *(pIter)>=0x80 && pIter<pEnd );
1393 }
1394 pIter++;
1395 pInfo->nKey = nPayload;
1396 pInfo->nPayload = nPayload;
1397 pInfo->pPayload = pIter;
1398 testcase( nPayload==pPage->maxLocal );
1399 testcase( nPayload==(u32)pPage->maxLocal+1 );
1400 assert( nPayload>=0 );
1401 assert( pPage->maxLocal <= BT_MAX_LOCAL );
1402 if( nPayload<=pPage->maxLocal ){
1403 /* This is the (easy) common case where the entire payload fits
1404 ** on the local page. No overflow is required.
1405 */
1406 pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell);
1407 if( pInfo->nSize<4 ) pInfo->nSize = 4;
1408 pInfo->nLocal = (u16)nPayload;
1409 }else{
1410 btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
1411 }
1412}
1413static void btreeParseCell(
1414 MemPage *pPage, /* Page containing the cell */
1415 int iCell, /* The cell index. First cell is 0 */
1416 CellInfo *pInfo /* Fill in this structure */
1417){
1418 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
1419}
1420
1421/*
1422** The following routines are implementations of the MemPage.xCellSize
1423** method.
1424**
1425** Compute the total number of bytes that a Cell needs in the cell
1426** data area of the btree-page. The return number includes the cell
1427** data header and the local payload, but not any overflow page or
1428** the space used by the cell pointer.
1429**
1430** cellSizePtrNoPayload() => table internal nodes
1431** cellSizePtrTableLeaf() => table leaf nodes
1432** cellSizePtr() => index internal nodes
1433** cellSizeIdxLeaf() => index leaf nodes
1434*/
1435static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
1436 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1437 u8 *pEnd; /* End mark for a varint */
1438 u32 nSize; /* Size value to return */
1439
1440#ifdef SQLITE_DEBUG
1441 /* The value returned by this function should always be the same as
1442 ** the (CellInfo.nSize) value found by doing a full parse of the
1443 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1444 ** this function verifies that this invariant is not violated. */
1445 CellInfo debuginfo;
1446 pPage->xParseCell(pPage, pCell, &debuginfo);
1447#endif
1448
1449 assert( pPage->childPtrSize==4 );
1450 nSize = *pIter;
1451 if( nSize>=0x80 ){
1452 pEnd = &pIter[8];
1453 nSize &= 0x7f;
1454 do{
1455 nSize = (nSize<<7) | (*++pIter & 0x7f);
1456 }while( *(pIter)>=0x80 && pIter<pEnd );
1457 }
1458 pIter++;
1459 testcase( nSize==pPage->maxLocal );
1460 testcase( nSize==(u32)pPage->maxLocal+1 );
1461 if( nSize<=pPage->maxLocal ){
1462 nSize += (u32)(pIter - pCell);
1463 assert( nSize>4 );
1464 }else{
1465 int minLocal = pPage->minLocal;
1466 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1467 testcase( nSize==pPage->maxLocal );
1468 testcase( nSize==(u32)pPage->maxLocal+1 );
1469 if( nSize>pPage->maxLocal ){
1470 nSize = minLocal;
1471 }
1472 nSize += 4 + (u16)(pIter - pCell);
1473 }
1474 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1475 return (u16)nSize;
1476}
1477static u16 cellSizePtrIdxLeaf(MemPage *pPage, u8 *pCell){
1478 u8 *pIter = pCell; /* For looping over bytes of pCell */
1479 u8 *pEnd; /* End mark for a varint */
1480 u32 nSize; /* Size value to return */
1481
1482#ifdef SQLITE_DEBUG
1483 /* The value returned by this function should always be the same as
1484 ** the (CellInfo.nSize) value found by doing a full parse of the
1485 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1486 ** this function verifies that this invariant is not violated. */
1487 CellInfo debuginfo;
1488 pPage->xParseCell(pPage, pCell, &debuginfo);
1489#endif
1490
1491 assert( pPage->childPtrSize==0 );
1492 nSize = *pIter;
1493 if( nSize>=0x80 ){
1494 pEnd = &pIter[8];
1495 nSize &= 0x7f;
1496 do{
1497 nSize = (nSize<<7) | (*++pIter & 0x7f);
1498 }while( *(pIter)>=0x80 && pIter<pEnd );
1499 }
1500 pIter++;
1501 testcase( nSize==pPage->maxLocal );
1502 testcase( nSize==(u32)pPage->maxLocal+1 );
1503 if( nSize<=pPage->maxLocal ){
1504 nSize += (u32)(pIter - pCell);
1505 if( nSize<4 ) nSize = 4;
1506 }else{
1507 int minLocal = pPage->minLocal;
1508 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1509 testcase( nSize==pPage->maxLocal );
1510 testcase( nSize==(u32)pPage->maxLocal+1 );
1511 if( nSize>pPage->maxLocal ){
1512 nSize = minLocal;
1513 }
1514 nSize += 4 + (u16)(pIter - pCell);
1515 }
1516 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1517 return (u16)nSize;
1518}
1519static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
1520 u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
1521 u8 *pEnd; /* End mark for a varint */
1522
1523#ifdef SQLITE_DEBUG
1524 /* The value returned by this function should always be the same as
1525 ** the (CellInfo.nSize) value found by doing a full parse of the
1526 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1527 ** this function verifies that this invariant is not violated. */
1528 CellInfo debuginfo;
1529 pPage->xParseCell(pPage, pCell, &debuginfo);
1530#else
1531 UNUSED_PARAMETER(pPage);
1532#endif
1533
1534 assert( pPage->childPtrSize==4 );
1535 pEnd = pIter + 9;
1536 while( (*pIter++)&0x80 && pIter<pEnd );
1537 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
1538 return (u16)(pIter - pCell);
1539}
1540static u16 cellSizePtrTableLeaf(MemPage *pPage, u8 *pCell){
1541 u8 *pIter = pCell; /* For looping over bytes of pCell */
1542 u8 *pEnd; /* End mark for a varint */
1543 u32 nSize; /* Size value to return */
1544
1545#ifdef SQLITE_DEBUG
1546 /* The value returned by this function should always be the same as
1547 ** the (CellInfo.nSize) value found by doing a full parse of the
1548 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
1549 ** this function verifies that this invariant is not violated. */
1550 CellInfo debuginfo;
1551 pPage->xParseCell(pPage, pCell, &debuginfo);
1552#endif
1553
1554 nSize = *pIter;
1555 if( nSize>=0x80 ){
1556 pEnd = &pIter[8];
1557 nSize &= 0x7f;
1558 do{
1559 nSize = (nSize<<7) | (*++pIter & 0x7f);
1560 }while( *(pIter)>=0x80 && pIter<pEnd );
1561 }
1562 pIter++;
1563 /* pIter now points at the 64-bit integer key value, a variable length
1564 ** integer. The following block moves pIter to point at the first byte
1565 ** past the end of the key value. */
1566 if( (*pIter++)&0x80
1567 && (*pIter++)&0x80
1568 && (*pIter++)&0x80
1569 && (*pIter++)&0x80
1570 && (*pIter++)&0x80
1571 && (*pIter++)&0x80
1572 && (*pIter++)&0x80
1573 && (*pIter++)&0x80 ){ pIter++; }
1574 testcase( nSize==pPage->maxLocal );
1575 testcase( nSize==(u32)pPage->maxLocal+1 );
1576 if( nSize<=pPage->maxLocal ){
1577 nSize += (u32)(pIter - pCell);
1578 if( nSize<4 ) nSize = 4;
1579 }else{
1580 int minLocal = pPage->minLocal;
1581 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
1582 testcase( nSize==pPage->maxLocal );
1583 testcase( nSize==(u32)pPage->maxLocal+1 );
1584 if( nSize>pPage->maxLocal ){
1585 nSize = minLocal;
1586 }
1587 nSize += 4 + (u16)(pIter - pCell);
1588 }
1589 assert( nSize==debuginfo.nSize || CORRUPT_DB );
1590 return (u16)nSize;
1591}
1592
1593
1594#ifdef SQLITE_DEBUG
1595/* This variation on cellSizePtr() is used inside of assert() statements
1596** only. */
1597static u16 cellSize(MemPage *pPage, int iCell){
1598 return pPage->xCellSize(pPage, findCell(pPage, iCell));
1599}
1600#endif
1601
1602#ifndef SQLITE_OMIT_AUTOVACUUM
1603/*
1604** The cell pCell is currently part of page pSrc but will ultimately be part
1605** of pPage. (pSrc and pPage are often the same.) If pCell contains a
1606** pointer to an overflow page, insert an entry into the pointer-map for
1607** the overflow page that will be valid after pCell has been moved to pPage.
1608*/
1609static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
1610 CellInfo info;
1611 if( *pRC ) return;
1612 assert( pCell!=0 );
1613 pPage->xParseCell(pPage, pCell, &info);
1614 if( info.nLocal<info.nPayload ){
1615 Pgno ovfl;
1616 if( SQLITE_OVERFLOW(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
1617 testcase( pSrc!=pPage );
1618 *pRC = SQLITE_CORRUPT_BKPT;
1619 return;
1620 }
1621 ovfl = get4byte(&pCell[info.nSize-4]);
1622 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
1623 }
1624}
1625#endif
1626
1627
1628/*
1629** Defragment the page given. This routine reorganizes cells within the
1630** page so that there are no free-blocks on the free-block list.
1631**
1632** Parameter nMaxFrag is the maximum amount of fragmented space that may be
1633** present in the page after this routine returns.
1634**
1635** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
1636** b-tree page so that there are no freeblocks or fragment bytes, all
1637** unused bytes are contained in the unallocated space region, and all
1638** cells are packed tightly at the end of the page.
1639*/
1640static int defragmentPage(MemPage *pPage, int nMaxFrag){
1641 int i; /* Loop counter */
1642 int pc; /* Address of the i-th cell */
1643 int hdr; /* Offset to the page header */
1644 int size; /* Size of a cell */
1645 int usableSize; /* Number of usable bytes on a page */
1646 int cellOffset; /* Offset to the cell pointer array */
1647 int cbrk; /* Offset to the cell content area */
1648 int nCell; /* Number of cells on the page */
1649 unsigned char *data; /* The page data */
1650 unsigned char *temp; /* Temp area for cell content */
1651 unsigned char *src; /* Source of content */
1652 int iCellFirst; /* First allowable cell index */
1653 int iCellLast; /* Last possible cell index */
1654 int iCellStart; /* First cell offset in input */
1655
1656 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1657 assert( pPage->pBt!=0 );
1658 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
1659 assert( pPage->nOverflow==0 );
1660 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1661 data = pPage->aData;
1662 hdr = pPage->hdrOffset;
1663 cellOffset = pPage->cellOffset;
1664 nCell = pPage->nCell;
1665 assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
1666 iCellFirst = cellOffset + 2*nCell;
1667 usableSize = pPage->pBt->usableSize;
1668
1669 /* This block handles pages with two or fewer free blocks and nMaxFrag
1670 ** or fewer fragmented bytes. In this case it is faster to move the
1671 ** two (or one) blocks of cells using memmove() and add the required
1672 ** offsets to each pointer in the cell-pointer array than it is to
1673 ** reconstruct the entire page. */
1674 if( (int)data[hdr+7]<=nMaxFrag ){
1675 int iFree = get2byte(&data[hdr+1]);
1676 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1677 if( iFree ){
1678 int iFree2 = get2byte(&data[iFree]);
1679 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
1680 if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
1681 u8 *pEnd = &data[cellOffset + nCell*2];
1682 u8 *pAddr;
1683 int sz2 = 0;
1684 int sz = get2byte(&data[iFree+2]);
1685 int top = get2byte(&data[hdr+5]);
1686 if( top>=iFree ){
1687 return SQLITE_CORRUPT_PAGE(pPage);
1688 }
1689 if( iFree2 ){
1690 if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
1691 sz2 = get2byte(&data[iFree2+2]);
1692 if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
1693 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
1694 sz += sz2;
1695 }else if( iFree+sz>usableSize ){
1696 return SQLITE_CORRUPT_PAGE(pPage);
1697 }
1698
1699 cbrk = top+sz;
1700 assert( cbrk+(iFree-top) <= usableSize );
1701 memmove(&data[cbrk], &data[top], iFree-top);
1702 for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
1703 pc = get2byte(pAddr);
1704 if( pc<iFree ){ put2byte(pAddr, pc+sz); }
1705 else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
1706 }
1707 goto defragment_out;
1708 }
1709 }
1710 }
1711
1712 cbrk = usableSize;
1713 iCellLast = usableSize - 4;
1714 iCellStart = get2byte(&data[hdr+5]);
1715 if( nCell>0 ){
1716 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
1717 memcpy(temp, data, usableSize);
1718 src = temp;
1719 for(i=0; i<nCell; i++){
1720 u8 *pAddr; /* The i-th cell pointer */
1721 pAddr = &data[cellOffset + i*2];
1722 pc = get2byte(pAddr);
1723 testcase( pc==iCellFirst );
1724 testcase( pc==iCellLast );
1725 /* These conditions have already been verified in btreeInitPage()
1726 ** if PRAGMA cell_size_check=ON.
1727 */
1728 if( pc>iCellLast ){
1729 return SQLITE_CORRUPT_PAGE(pPage);
1730 }
1731 assert( pc>=0 && pc<=iCellLast );
1732 size = pPage->xCellSize(pPage, &src[pc]);
1733 cbrk -= size;
1734 if( cbrk<iCellStart || pc+size>usableSize ){
1735 return SQLITE_CORRUPT_PAGE(pPage);
1736 }
1737 assert( cbrk+size<=usableSize && cbrk>=iCellStart );
1738 testcase( cbrk+size==usableSize );
1739 testcase( pc+size==usableSize );
1740 put2byte(pAddr, cbrk);
1741 memcpy(&data[cbrk], &src[pc], size);
1742 }
1743 }
1744 data[hdr+7] = 0;
1745
1746defragment_out:
1747 assert( pPage->nFree>=0 );
1748 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
1749 return SQLITE_CORRUPT_PAGE(pPage);
1750 }
1751 assert( cbrk>=iCellFirst );
1752 put2byte(&data[hdr+5], cbrk);
1753 data[hdr+1] = 0;
1754 data[hdr+2] = 0;
1755 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
1756 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1757 return SQLITE_OK;
1758}
1759
1760/*
1761** Search the free-list on page pPg for space to store a cell nByte bytes in
1762** size. If one can be found, return a pointer to the space and remove it
1763** from the free-list.
1764**
1765** If no suitable space can be found on the free-list, return NULL.
1766**
1767** This function may detect corruption within pPg. If corruption is
1768** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
1769**
1770** Slots on the free list that are between 1 and 3 bytes larger than nByte
1771** will be ignored if adding the extra space to the fragmentation count
1772** causes the fragmentation count to exceed 60.
1773*/
1774static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
1775 const int hdr = pPg->hdrOffset; /* Offset to page header */
1776 u8 * const aData = pPg->aData; /* Page data */
1777 int iAddr = hdr + 1; /* Address of ptr to pc */
1778 u8 *pTmp = &aData[iAddr]; /* Temporary ptr into aData[] */
1779 int pc = get2byte(pTmp); /* Address of a free slot */
1780 int x; /* Excess size of the slot */
1781 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
1782 int size; /* Size of the free slot */
1783
1784 assert( pc>0 );
1785 while( pc<=maxPC ){
1786 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
1787 ** freeblock form a big-endian integer which is the size of the freeblock
1788 ** in bytes, including the 4-byte header. */
1789 pTmp = &aData[pc+2];
1790 size = get2byte(pTmp);
1791 if( (x = size - nByte)>=0 ){
1792 testcase( x==4 );
1793 testcase( x==3 );
1794 if( x<4 ){
1795 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
1796 ** number of bytes in fragments may not exceed 60. */
1797 if( aData[hdr+7]>57 ) return 0;
1798
1799 /* Remove the slot from the free-list. Update the number of
1800 ** fragmented bytes within the page. */
1801 memcpy(&aData[iAddr], &aData[pc], 2);
1802 aData[hdr+7] += (u8)x;
1803 return &aData[pc];
1804 }else if( x+pc > maxPC ){
1805 /* This slot extends off the end of the usable part of the page */
1806 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1807 return 0;
1808 }else{
1809 /* The slot remains on the free-list. Reduce its size to account
1810 ** for the portion used by the new allocation. */
1811 put2byte(&aData[pc+2], x);
1812 }
1813 return &aData[pc + x];
1814 }
1815 iAddr = pc;
1816 pTmp = &aData[pc];
1817 pc = get2byte(pTmp);
1818 if( pc<=iAddr ){
1819 if( pc ){
1820 /* The next slot in the chain comes before the current slot */
1821 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1822 }
1823 return 0;
1824 }
1825 }
1826 if( pc>maxPC+nByte-4 ){
1827 /* The free slot chain extends off the end of the page */
1828 *pRc = SQLITE_CORRUPT_PAGE(pPg);
1829 }
1830 return 0;
1831}
1832
1833/*
1834** Allocate nByte bytes of space from within the B-Tree page passed
1835** as the first argument. Write into *pIdx the index into pPage->aData[]
1836** of the first byte of allocated space. Return either SQLITE_OK or
1837** an error code (usually SQLITE_CORRUPT).
1838**
1839** The caller guarantees that there is sufficient space to make the
1840** allocation. This routine might need to defragment in order to bring
1841** all the space together, however. This routine will avoid using
1842** the first two bytes past the cell pointer area since presumably this
1843** allocation is being made in order to insert a new cell, so we will
1844** also end up needing a new cell pointer.
1845*/
1846static SQLITE_INLINE int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
1847 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
1848 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
1849 int top; /* First byte of cell content area */
1850 int rc = SQLITE_OK; /* Integer return code */
1851 u8 *pTmp; /* Temp ptr into data[] */
1852 int gap; /* First byte of gap between cell pointers and cell content */
1853
1854 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1855 assert( pPage->pBt );
1856 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1857 assert( nByte>=0 ); /* Minimum cell size is 4 */
1858 assert( pPage->nFree>=nByte );
1859 assert( pPage->nOverflow==0 );
1860 assert( nByte < (int)(pPage->pBt->usableSize-8) );
1861
1862 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1863 gap = pPage->cellOffset + 2*pPage->nCell;
1864 assert( gap<=65536 );
1865 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
1866 ** and the reserved space is zero (the usual value for reserved space)
1867 ** then the cell content offset of an empty page wants to be 65536.
1868 ** However, that integer is too large to be stored in a 2-byte unsigned
1869 ** integer, so a value of 0 is used in its place. */
1870 pTmp = &data[hdr+5];
1871 top = get2byte(pTmp);
1872 if( gap>top ){
1873 if( top==0 && pPage->pBt->usableSize==65536 ){
1874 top = 65536;
1875 }else{
1876 return SQLITE_CORRUPT_PAGE(pPage);
1877 }
1878 }else if( top>(int)pPage->pBt->usableSize ){
1879 return SQLITE_CORRUPT_PAGE(pPage);
1880 }
1881
1882 /* If there is enough space between gap and top for one more cell pointer,
1883 ** and if the freelist is not empty, then search the
1884 ** freelist looking for a slot big enough to satisfy the request.
1885 */
1886 testcase( gap+2==top );
1887 testcase( gap+1==top );
1888 testcase( gap==top );
1889 if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
1890 u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
1891 if( pSpace ){
1892 int g2;
1893 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
1894 *pIdx = g2 = (int)(pSpace-data);
1895 if( g2<=gap ){
1896 return SQLITE_CORRUPT_PAGE(pPage);
1897 }else{
1898 return SQLITE_OK;
1899 }
1900 }else if( rc ){
1901 return rc;
1902 }
1903 }
1904
1905 /* The request could not be fulfilled using a freelist slot. Check
1906 ** to see if defragmentation is necessary.
1907 */
1908 testcase( gap+2+nByte==top );
1909 if( gap+2+nByte>top ){
1910 assert( pPage->nCell>0 || CORRUPT_DB );
1911 assert( pPage->nFree>=0 );
1912 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
1913 if( rc ) return rc;
1914 top = get2byteNotZero(&data[hdr+5]);
1915 assert( gap+2+nByte<=top );
1916 }
1917
1918
1919 /* Allocate memory from the gap in between the cell pointer array
1920 ** and the cell content area. The btreeComputeFreeSpace() call has already
1921 ** validated the freelist. Given that the freelist is valid, there
1922 ** is no way that the allocation can extend off the end of the page.
1923 ** The assert() below verifies the previous sentence.
1924 */
1925 top -= nByte;
1926 put2byte(&data[hdr+5], top);
1927 assert( top+nByte <= (int)pPage->pBt->usableSize );
1928 *pIdx = top;
1929 return SQLITE_OK;
1930}
1931
1932/*
1933** Return a section of the pPage->aData to the freelist.
1934** The first byte of the new free block is pPage->aData[iStart]
1935** and the size of the block is iSize bytes.
1936**
1937** Adjacent freeblocks are coalesced.
1938**
1939** Even though the freeblock list was checked by btreeComputeFreeSpace(),
1940** that routine will not detect overlap between cells or freeblocks. Nor
1941** does it detect cells or freeblocks that encroach into the reserved bytes
1942** at the end of the page. So do additional corruption checks inside this
1943** routine and return SQLITE_CORRUPT if any problems are found.
1944*/
1945static int freeSpace(MemPage *pPage, int iStart, int iSize){
1946 int iPtr; /* Address of ptr to next freeblock */
1947 int iFreeBlk; /* Address of the next freeblock */
1948 u8 hdr; /* Page header size. 0 or 100 */
1949 int nFrag = 0; /* Reduction in fragmentation */
1950 int iOrigSize = iSize; /* Original value of iSize */
1951 int x; /* Offset to cell content area */
1952 int iEnd = iStart + iSize; /* First byte past the iStart buffer */
1953 unsigned char *data = pPage->aData; /* Page content */
1954 u8 *pTmp; /* Temporary ptr into data[] */
1955
1956 assert( pPage->pBt!=0 );
1957 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1958 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
1959 assert( CORRUPT_DB || iEnd <= (int)pPage->pBt->usableSize );
1960 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1961 assert( iSize>=4 ); /* Minimum cell size is 4 */
1962 assert( CORRUPT_DB || iStart<=(int)pPage->pBt->usableSize-4 );
1963
1964 /* The list of freeblocks must be in ascending order. Find the
1965 ** spot on the list where iStart should be inserted.
1966 */
1967 hdr = pPage->hdrOffset;
1968 iPtr = hdr + 1;
1969 if( data[iPtr+1]==0 && data[iPtr]==0 ){
1970 iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
1971 }else{
1972 while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
1973 if( iFreeBlk<=iPtr ){
1974 if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
1975 return SQLITE_CORRUPT_PAGE(pPage);
1976 }
1977 iPtr = iFreeBlk;
1978 }
1979 if( iFreeBlk>(int)pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
1980 return SQLITE_CORRUPT_PAGE(pPage);
1981 }
1982 assert( iFreeBlk>iPtr || iFreeBlk==0 || CORRUPT_DB );
1983
1984 /* At this point:
1985 ** iFreeBlk: First freeblock after iStart, or zero if none
1986 ** iPtr: The address of a pointer to iFreeBlk
1987 **
1988 ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
1989 */
1990 if( iFreeBlk && iEnd+3>=iFreeBlk ){
1991 nFrag = iFreeBlk - iEnd;
1992 if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
1993 iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
1994 if( iEnd > (int)pPage->pBt->usableSize ){
1995 return SQLITE_CORRUPT_PAGE(pPage);
1996 }
1997 iSize = iEnd - iStart;
1998 iFreeBlk = get2byte(&data[iFreeBlk]);
1999 }
2000
2001 /* If iPtr is another freeblock (that is, if iPtr is not the freelist
2002 ** pointer in the page header) then check to see if iStart should be
2003 ** coalesced onto the end of iPtr.
2004 */
2005 if( iPtr>hdr+1 ){
2006 int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
2007 if( iPtrEnd+3>=iStart ){
2008 if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
2009 nFrag += iStart - iPtrEnd;
2010 iSize = iEnd - iPtr;
2011 iStart = iPtr;
2012 }
2013 }
2014 if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
2015 data[hdr+7] -= (u8)nFrag;
2016 }
2017 pTmp = &data[hdr+5];
2018 x = get2byte(pTmp);
2019 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
2020 /* Overwrite deleted information with zeros when the secure_delete
2021 ** option is enabled */
2022 memset(&data[iStart], 0, iSize);
2023 }
2024 if( iStart<=x ){
2025 /* The new freeblock is at the beginning of the cell content area,
2026 ** so just extend the cell content area rather than create another
2027 ** freelist entry */
2028 if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
2029 if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
2030 put2byte(&data[hdr+1], iFreeBlk);
2031 put2byte(&data[hdr+5], iEnd);
2032 }else{
2033 /* Insert the new freeblock into the freelist */
2034 put2byte(&data[iPtr], iStart);
2035 put2byte(&data[iStart], iFreeBlk);
2036 assert( iSize>=0 && iSize<=0xffff );
2037 put2byte(&data[iStart+2], (u16)iSize);
2038 }
2039 pPage->nFree += iOrigSize;
2040 return SQLITE_OK;
2041}
2042
2043/*
2044** Decode the flags byte (the first byte of the header) for a page
2045** and initialize fields of the MemPage structure accordingly.
2046**
2047** Only the following combinations are supported. Anything different
2048** indicates a corrupt database files:
2049**
2050** PTF_ZERODATA (0x02, 2)
2051** PTF_LEAFDATA | PTF_INTKEY (0x05, 5)
2052** PTF_ZERODATA | PTF_LEAF (0x0a, 10)
2053** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF (0x0d, 13)
2054*/
2055static int decodeFlags(MemPage *pPage, int flagByte){
2056 BtShared *pBt; /* A copy of pPage->pBt */
2057
2058 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
2059 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2060 pBt = pPage->pBt;
2061 pPage->max1bytePayload = pBt->max1bytePayload;
2062 if( flagByte>=(PTF_ZERODATA | PTF_LEAF) ){
2063 pPage->childPtrSize = 0;
2064 pPage->leaf = 1;
2065 if( flagByte==(PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF) ){
2066 pPage->intKeyLeaf = 1;
2067 pPage->xCellSize = cellSizePtrTableLeaf;
2068 pPage->xParseCell = btreeParseCellPtr;
2069 pPage->intKey = 1;
2070 pPage->maxLocal = pBt->maxLeaf;
2071 pPage->minLocal = pBt->minLeaf;
2072 }else if( flagByte==(PTF_ZERODATA | PTF_LEAF) ){
2073 pPage->intKey = 0;
2074 pPage->intKeyLeaf = 0;
2075 pPage->xCellSize = cellSizePtrIdxLeaf;
2076 pPage->xParseCell = btreeParseCellPtrIndex;
2077 pPage->maxLocal = pBt->maxLocal;
2078 pPage->minLocal = pBt->minLocal;
2079 }else{
2080 pPage->intKey = 0;
2081 pPage->intKeyLeaf = 0;
2082 pPage->xCellSize = cellSizePtrIdxLeaf;
2083 pPage->xParseCell = btreeParseCellPtrIndex;
2084 return SQLITE_CORRUPT_PAGE(pPage);
2085 }
2086 }else{
2087 pPage->childPtrSize = 4;
2088 pPage->leaf = 0;
2089 if( flagByte==(PTF_ZERODATA) ){
2090 pPage->intKey = 0;
2091 pPage->intKeyLeaf = 0;
2092 pPage->xCellSize = cellSizePtr;
2093 pPage->xParseCell = btreeParseCellPtrIndex;
2094 pPage->maxLocal = pBt->maxLocal;
2095 pPage->minLocal = pBt->minLocal;
2096 }else if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
2097 pPage->intKeyLeaf = 0;
2098 pPage->xCellSize = cellSizePtrNoPayload;
2099 pPage->xParseCell = btreeParseCellPtrNoPayload;
2100 pPage->intKey = 1;
2101 pPage->maxLocal = pBt->maxLeaf;
2102 pPage->minLocal = pBt->minLeaf;
2103 }else{
2104 pPage->intKey = 0;
2105 pPage->intKeyLeaf = 0;
2106 pPage->xCellSize = cellSizePtr;
2107 pPage->xParseCell = btreeParseCellPtrIndex;
2108 return SQLITE_CORRUPT_PAGE(pPage);
2109 }
2110 }
2111 return SQLITE_OK;
2112}
2113
2114/*
2115** Compute the amount of freespace on the page. In other words, fill
2116** in the pPage->nFree field.
2117*/
2118static int btreeComputeFreeSpace(MemPage *pPage){
2119 int pc; /* Address of a freeblock within pPage->aData[] */
2120 u8 hdr; /* Offset to beginning of page header */
2121 u8 *data; /* Equal to pPage->aData */
2122 int usableSize; /* Amount of usable space on each page */
2123 int nFree; /* Number of unused bytes on the page */
2124 int top; /* First byte of the cell content area */
2125 int iCellFirst; /* First allowable cell or freeblock offset */
2126 int iCellLast; /* Last possible cell or freeblock offset */
2127
2128 assert( pPage->pBt!=0 );
2129 assert( pPage->pBt->db!=0 );
2130 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2131 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2132 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2133 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2134 assert( pPage->isInit==1 );
2135 assert( pPage->nFree<0 );
2136
2137 usableSize = pPage->pBt->usableSize;
2138 hdr = pPage->hdrOffset;
2139 data = pPage->aData;
2140 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
2141 ** the start of the cell content area. A zero value for this integer is
2142 ** interpreted as 65536. */
2143 top = get2byteNotZero(&data[hdr+5]);
2144 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
2145 iCellLast = usableSize - 4;
2146
2147 /* Compute the total free space on the page
2148 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
2149 ** start of the first freeblock on the page, or is zero if there are no
2150 ** freeblocks. */
2151 pc = get2byte(&data[hdr+1]);
2152 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
2153 if( pc>0 ){
2154 u32 next, size;
2155 if( pc<top ){
2156 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
2157 ** always be at least one cell before the first freeblock.
2158 */
2159 return SQLITE_CORRUPT_PAGE(pPage);
2160 }
2161 while( 1 ){
2162 if( pc>iCellLast ){
2163 /* Freeblock off the end of the page */
2164 return SQLITE_CORRUPT_PAGE(pPage);
2165 }
2166 next = get2byte(&data[pc]);
2167 size = get2byte(&data[pc+2]);
2168 if( size<4 && sqlite3FaultSim(422)==SQLITE_OK ){
2169 /* Minimum freeblock size is 4. Enable fault-sim 422 to disable this
2170 ** check to reach interesting error states. However, disabling this
2171 ** check can cause assertion faults due to min-heap overflow. All
2172 ** fault-sims are for testing use only, but this one especially so. */
2173 return SQLITE_CORRUPT_PAGE(pPage);
2174 }
2175 nFree = nFree + size;
2176 if( next<pc+size+4 ) break;
2177 pc = next;
2178 }
2179 if( next>0 ){
2180 /* Freeblock not in ascending order */
2181 return SQLITE_CORRUPT_PAGE(pPage);
2182 }
2183 if( pc+size>(unsigned int)usableSize ){
2184 /* Last freeblock extends past page end */
2185 return SQLITE_CORRUPT_PAGE(pPage);
2186 }
2187 }
2188
2189 /* At this point, nFree contains the sum of the offset to the start
2190 ** of the cell-content area plus the number of free bytes within
2191 ** the cell-content area. If this is greater than the usable-size
2192 ** of the page, then the page must be corrupted. This check also
2193 ** serves to verify that the offset to the start of the cell-content
2194 ** area, according to the page header, lies within the page.
2195 */
2196 if( nFree>usableSize || nFree<iCellFirst ){
2197 return SQLITE_CORRUPT_PAGE(pPage);
2198 }
2199 pPage->nFree = (u16)(nFree - iCellFirst);
2200 return SQLITE_OK;
2201}
2202
2203/*
2204** Do additional sanity check after btreeInitPage() if
2205** PRAGMA cell_size_check=ON. Raise a corruption error and
2206** leave the page uninitialized if any problems are found.
2207*/
2208static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
2209 int iCellFirst; /* First allowable cell or freeblock offset */
2210 int iCellLast; /* Last possible cell or freeblock offset */
2211 int i; /* Index into the cell pointer array */
2212 int sz; /* Size of a cell */
2213 int pc; /* Address of a freeblock within pPage->aData[] */
2214 u8 *data; /* Equal to pPage->aData */
2215 int usableSize; /* Maximum usable space on the page */
2216 int cellOffset; /* Start of cell content area */
2217
2218 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
2219 usableSize = pPage->pBt->usableSize;
2220 iCellLast = usableSize - 4;
2221 data = pPage->aData;
2222 cellOffset = pPage->cellOffset;
2223 if( !pPage->leaf ) iCellLast--;
2224 for(i=0; i<pPage->nCell; i++){
2225 pc = get2byteAligned(&data[cellOffset+i*2]);
2226 testcase( pc==iCellFirst );
2227 testcase( pc==iCellLast );
2228 if( pc<iCellFirst || pc>iCellLast ){
2229 pPage->isInit = 0;
2230 return SQLITE_CORRUPT_PAGE(pPage);
2231 }
2232 sz = pPage->xCellSize(pPage, &data[pc]);
2233 testcase( pc+sz==usableSize );
2234 if( pc+sz>usableSize ){
2235 pPage->isInit = 0;
2236 return SQLITE_CORRUPT_PAGE(pPage);
2237 }
2238 }
2239 return SQLITE_OK;
2240}
2241
2242/*
2243** Initialize the auxiliary information for a disk block.
2244**
2245** Return SQLITE_OK on success. If we see that the page does
2246** not contain a well-formed database page, then return
2247** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
2248** guarantee that the page is well-formed. It only shows that
2249** we failed to detect any corruption.
2250*/
2251static int btreeInitPage(MemPage *pPage){
2252 u8 *data; /* Equal to pPage->aData */
2253 BtShared *pBt; /* The main btree structure */
2254
2255 assert( pPage->pBt!=0 );
2256 assert( pPage->pBt->db!=0 );
2257 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2258 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
2259 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
2260 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
2261 assert( pPage->isInit==0 );
2262
2263 pBt = pPage->pBt;
2264 data = pPage->aData + pPage->hdrOffset;
2265 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
2266 ** the b-tree page type. */
2267 if( decodeFlags(pPage, data[0]) ){
2268 return SQLITE_CORRUPT_PAGE(pPage);
2269 }
2270 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2271 pPage->maskPage = (u16)(pBt->pageSize - 1);
2272 pPage->nOverflow = 0;
2273 pPage->cellOffset = (u16)(pPage->hdrOffset + 8 + pPage->childPtrSize);
2274 pPage->aCellIdx = data + pPage->childPtrSize + 8;
2275 pPage->aDataEnd = pPage->aData + pBt->pageSize;
2276 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
2277 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
2278 ** number of cells on the page. */
2279 pPage->nCell = get2byte(&data[3]);
2280 if( pPage->nCell>MX_CELL(pBt) ){
2281 /* To many cells for a single page. The page must be corrupt */
2282 return SQLITE_CORRUPT_PAGE(pPage);
2283 }
2284 testcase( pPage->nCell==MX_CELL(pBt) );
2285 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
2286 ** possible for a root page of a table that contains no rows) then the
2287 ** offset to the cell content area will equal the page size minus the
2288 ** bytes of reserved space. */
2289 assert( pPage->nCell>0
2290 || get2byteNotZero(&data[5])==(int)pBt->usableSize
2291 || CORRUPT_DB );
2292 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
2293 pPage->isInit = 1;
2294 if( pBt->db->flags & SQLITE_CellSizeCk ){
2295 return btreeCellSizeCheck(pPage);
2296 }
2297 return SQLITE_OK;
2298}
2299
2300/*
2301** Set up a raw page so that it looks like a database page holding
2302** no entries.
2303*/
2304static void zeroPage(MemPage *pPage, int flags){
2305 unsigned char *data = pPage->aData;
2306 BtShared *pBt = pPage->pBt;
2307 int hdr = pPage->hdrOffset;
2308 int first;
2309
2310 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
2311 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2312 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
2313 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
2314 assert( sqlite3_mutex_held(pBt->mutex) );
2315 if( pBt->btsFlags & BTS_FAST_SECURE ){
2316 memset(&data[hdr], 0, pBt->usableSize - hdr);
2317 }
2318 data[hdr] = (char)flags;
2319 first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
2320 memset(&data[hdr+1], 0, 4);
2321 data[hdr+7] = 0;
2322 put2byte(&data[hdr+5], pBt->usableSize);
2323 pPage->nFree = (u16)(pBt->usableSize - first);
2324 decodeFlags(pPage, flags);
2325 pPage->cellOffset = (u16)first;
2326 pPage->aDataEnd = &data[pBt->pageSize];
2327 pPage->aCellIdx = &data[first];
2328 pPage->aDataOfst = &data[pPage->childPtrSize];
2329 pPage->nOverflow = 0;
2330 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
2331 pPage->maskPage = (u16)(pBt->pageSize - 1);
2332 pPage->nCell = 0;
2333 pPage->isInit = 1;
2334}
2335
2336
2337/*
2338** Convert a DbPage obtained from the pager into a MemPage used by
2339** the btree layer.
2340*/
2341static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
2342 MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2343 if( pgno!=pPage->pgno ){
2344 pPage->aData = sqlite3PagerGetData(pDbPage);
2345 pPage->pDbPage = pDbPage;
2346 pPage->pBt = pBt;
2347 pPage->pgno = pgno;
2348 pPage->hdrOffset = pgno==1 ? 100 : 0;
2349 }
2350 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2351 return pPage;
2352}
2353
2354/*
2355** Get a page from the pager. Initialize the MemPage.pBt and
2356** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
2357**
2358** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
2359** about the content of the page at this time. So do not go to the disk
2360** to fetch the content. Just fill in the content with zeros for now.
2361** If in the future we call sqlite3PagerWrite() on this page, that
2362** means we have started to be concerned about content and the disk
2363** read should occur at that point.
2364*/
2365static int btreeGetPage(
2366 BtShared *pBt, /* The btree */
2367 Pgno pgno, /* Number of the page to fetch */
2368 MemPage **ppPage, /* Return the page in this parameter */
2369 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2370){
2371 int rc;
2372 DbPage *pDbPage;
2373
2374 assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
2375 assert( sqlite3_mutex_held(pBt->mutex) );
2376 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
2377 if( rc ) return rc;
2378 *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
2379 return SQLITE_OK;
2380}
2381
2382/*
2383** Retrieve a page from the pager cache. If the requested page is not
2384** already in the pager cache return NULL. Initialize the MemPage.pBt and
2385** MemPage.aData elements if needed.
2386*/
2387static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
2388 DbPage *pDbPage;
2389 assert( sqlite3_mutex_held(pBt->mutex) );
2390 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
2391 if( pDbPage ){
2392 return btreePageFromDbPage(pDbPage, pgno, pBt);
2393 }
2394 return 0;
2395}
2396
2397/*
2398** Return the size of the database file in pages. If there is any kind of
2399** error, return ((unsigned int)-1).
2400*/
2401static Pgno btreePagecount(BtShared *pBt){
2402 return pBt->nPage;
2403}
2404Pgno sqlite3BtreeLastPage(Btree *p){
2405 assert( sqlite3BtreeHoldsMutex(p) );
2406 return btreePagecount(p->pBt);
2407}
2408
2409/*
2410** Get a page from the pager and initialize it.
2411*/
2412static int getAndInitPage(
2413 BtShared *pBt, /* The database file */
2414 Pgno pgno, /* Number of the page to get */
2415 MemPage **ppPage, /* Write the page pointer here */
2416 int bReadOnly /* True for a read-only page */
2417){
2418 int rc;
2419 DbPage *pDbPage;
2420 MemPage *pPage;
2421 assert( sqlite3_mutex_held(pBt->mutex) );
2422
2423 if( pgno>btreePagecount(pBt) ){
2424 *ppPage = 0;
2425 return SQLITE_CORRUPT_BKPT;
2426 }
2427 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
2428 if( rc ){
2429 *ppPage = 0;
2430 return rc;
2431 }
2432 pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
2433 if( pPage->isInit==0 ){
2434 btreePageFromDbPage(pDbPage, pgno, pBt);
2435 rc = btreeInitPage(pPage);
2436 if( rc!=SQLITE_OK ){
2437 releasePage(pPage);
2438 *ppPage = 0;
2439 return rc;
2440 }
2441 }
2442 assert( pPage->pgno==pgno || CORRUPT_DB );
2443 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
2444 *ppPage = pPage;
2445 return SQLITE_OK;
2446}
2447
2448/*
2449** Release a MemPage. This should be called once for each prior
2450** call to btreeGetPage.
2451**
2452** Page1 is a special case and must be released using releasePageOne().
2453*/
2454static void releasePageNotNull(MemPage *pPage){
2455 assert( pPage->aData );
2456 assert( pPage->pBt );
2457 assert( pPage->pDbPage!=0 );
2458 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2459 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2460 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2461 sqlite3PagerUnrefNotNull(pPage->pDbPage);
2462}
2463static void releasePage(MemPage *pPage){
2464 if( pPage ) releasePageNotNull(pPage);
2465}
2466static void releasePageOne(MemPage *pPage){
2467 assert( pPage!=0 );
2468 assert( pPage->aData );
2469 assert( pPage->pBt );
2470 assert( pPage->pDbPage!=0 );
2471 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
2472 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
2473 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2474 sqlite3PagerUnrefPageOne(pPage->pDbPage);
2475}
2476
2477/*
2478** Get an unused page.
2479**
2480** This works just like btreeGetPage() with the addition:
2481**
2482** * If the page is already in use for some other purpose, immediately
2483** release it and return an SQLITE_CURRUPT error.
2484** * Make sure the isInit flag is clear
2485*/
2486static int btreeGetUnusedPage(
2487 BtShared *pBt, /* The btree */
2488 Pgno pgno, /* Number of the page to fetch */
2489 MemPage **ppPage, /* Return the page in this parameter */
2490 int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
2491){
2492 int rc = btreeGetPage(pBt, pgno, ppPage, flags);
2493 if( rc==SQLITE_OK ){
2494 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
2495 releasePage(*ppPage);
2496 *ppPage = 0;
2497 return SQLITE_CORRUPT_BKPT;
2498 }
2499 (*ppPage)->isInit = 0;
2500 }else{
2501 *ppPage = 0;
2502 }
2503 return rc;
2504}
2505
2506
2507/*
2508** During a rollback, when the pager reloads information into the cache
2509** so that the cache is restored to its original state at the start of
2510** the transaction, for each page restored this routine is called.
2511**
2512** This routine needs to reset the extra data section at the end of the
2513** page to agree with the restored data.
2514*/
2515static void pageReinit(DbPage *pData){
2516 MemPage *pPage;
2517 pPage = (MemPage *)sqlite3PagerGetExtra(pData);
2518 assert( sqlite3PagerPageRefcount(pData)>0 );
2519 if( pPage->isInit ){
2520 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
2521 pPage->isInit = 0;
2522 if( sqlite3PagerPageRefcount(pData)>1 ){
2523 /* pPage might not be a btree page; it might be an overflow page
2524 ** or ptrmap page or a free page. In those cases, the following
2525 ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
2526 ** But no harm is done by this. And it is very important that
2527 ** btreeInitPage() be called on every btree page so we make
2528 ** the call for every page that comes in for re-initializing. */
2529 btreeInitPage(pPage);
2530 }
2531 }
2532}
2533
2534/*
2535** Invoke the busy handler for a btree.
2536*/
2537static int btreeInvokeBusyHandler(void *pArg){
2538 BtShared *pBt = (BtShared*)pArg;
2539 assert( pBt->db );
2540 assert( sqlite3_mutex_held(pBt->db->mutex) );
2541 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
2542}
2543
2544/*
2545** Open a database file.
2546**
2547** zFilename is the name of the database file. If zFilename is NULL
2548** then an ephemeral database is created. The ephemeral database might
2549** be exclusively in memory, or it might use a disk-based memory cache.
2550** Either way, the ephemeral database will be automatically deleted
2551** when sqlite3BtreeClose() is called.
2552**
2553** If zFilename is ":memory:" then an in-memory database is created
2554** that is automatically destroyed when it is closed.
2555**
2556** The "flags" parameter is a bitmask that might contain bits like
2557** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
2558**
2559** If the database is already opened in the same database connection
2560** and we are in shared cache mode, then the open will fail with an
2561** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
2562** objects in the same database connection since doing so will lead
2563** to problems with locking.
2564*/
2565int sqlite3BtreeOpen(
2566 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
2567 const char *zFilename, /* Name of the file containing the BTree database */
2568 sqlite3 *db, /* Associated database handle */
2569 Btree **ppBtree, /* Pointer to new Btree object written here */
2570 int flags, /* Options */
2571 int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
2572){
2573 BtShared *pBt = 0; /* Shared part of btree structure */
2574 Btree *p; /* Handle to return */
2575 sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
2576 int rc = SQLITE_OK; /* Result code from this function */
2577 u8 nReserve; /* Byte of unused space on each page */
2578 unsigned char zDbHeader[100]; /* Database header content */
2579
2580 /* True if opening an ephemeral, temporary database */
2581 const int isTempDb = zFilename==0 || zFilename[0]==0;
2582
2583 /* Set the variable isMemdb to true for an in-memory database, or
2584 ** false for a file-based database.
2585 */
2586#ifdef SQLITE_OMIT_MEMORYDB
2587 const int isMemdb = 0;
2588#else
2589 const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
2590 || (isTempDb && sqlite3TempInMemory(db))
2591 || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
2592#endif
2593
2594 assert( db!=0 );
2595 assert( pVfs!=0 );
2596 assert( sqlite3_mutex_held(db->mutex) );
2597 assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
2598
2599 /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
2600 assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
2601
2602 /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
2603 assert( (flags & BTREE_SINGLE)==0 || isTempDb );
2604
2605 if( isMemdb ){
2606 flags |= BTREE_MEMORY;
2607 }
2608 if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
2609 vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
2610 }
2611 p = sqlite3MallocZero(sizeof(Btree));
2612 if( !p ){
2613 return SQLITE_NOMEM_BKPT;
2614 }
2615 p->inTrans = TRANS_NONE;
2616 p->db = db;
2617#ifndef SQLITE_OMIT_SHARED_CACHE
2618 p->lock.pBtree = p;
2619 p->lock.iTable = 1;
2620#endif
2621
2622#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2623 /*
2624 ** If this Btree is a candidate for shared cache, try to find an
2625 ** existing BtShared object that we can share with
2626 */
2627 if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
2628 if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
2629 int nFilename = sqlite3Strlen30(zFilename)+1;
2630 int nFullPathname = pVfs->mxPathname+1;
2631 char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
2632 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2633
2634 p->sharable = 1;
2635 if( !zFullPathname ){
2636 sqlite3_free(p);
2637 return SQLITE_NOMEM_BKPT;
2638 }
2639 if( isMemdb ){
2640 memcpy(zFullPathname, zFilename, nFilename);
2641 }else{
2642 rc = sqlite3OsFullPathname(pVfs, zFilename,
2643 nFullPathname, zFullPathname);
2644 if( rc ){
2645 if( rc==SQLITE_OK_SYMLINK ){
2646 rc = SQLITE_OK;
2647 }else{
2648 sqlite3_free(zFullPathname);
2649 sqlite3_free(p);
2650 return rc;
2651 }
2652 }
2653 }
2654#if SQLITE_THREADSAFE
2655 mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
2656 sqlite3_mutex_enter(mutexOpen);
2657 mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);
2658 sqlite3_mutex_enter(mutexShared);
2659#endif
2660 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
2661 assert( pBt->nRef>0 );
2662 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
2663 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
2664 int iDb;
2665 for(iDb=db->nDb-1; iDb>=0; iDb--){
2666 Btree *pExisting = db->aDb[iDb].pBt;
2667 if( pExisting && pExisting->pBt==pBt ){
2668 sqlite3_mutex_leave(mutexShared);
2669 sqlite3_mutex_leave(mutexOpen);
2670 sqlite3_free(zFullPathname);
2671 sqlite3_free(p);
2672 return SQLITE_CONSTRAINT;
2673 }
2674 }
2675 p->pBt = pBt;
2676 pBt->nRef++;
2677 break;
2678 }
2679 }
2680 sqlite3_mutex_leave(mutexShared);
2681 sqlite3_free(zFullPathname);
2682 }
2683#ifdef SQLITE_DEBUG
2684 else{
2685 /* In debug mode, we mark all persistent databases as sharable
2686 ** even when they are not. This exercises the locking code and
2687 ** gives more opportunity for asserts(sqlite3_mutex_held())
2688 ** statements to find locking problems.
2689 */
2690 p->sharable = 1;
2691 }
2692#endif
2693 }
2694#endif
2695 if( pBt==0 ){
2696 /*
2697 ** The following asserts make sure that structures used by the btree are
2698 ** the right size. This is to guard against size changes that result
2699 ** when compiling on a different architecture.
2700 */
2701 assert( sizeof(i64)==8 );
2702 assert( sizeof(u64)==8 );
2703 assert( sizeof(u32)==4 );
2704 assert( sizeof(u16)==2 );
2705 assert( sizeof(Pgno)==4 );
2706
2707 /* Suppress false-positive compiler warning from PVS-Studio */
2708 memset(&zDbHeader[16], 0, 8);
2709
2710 pBt = sqlite3MallocZero( sizeof(*pBt) );
2711 if( pBt==0 ){
2712 rc = SQLITE_NOMEM_BKPT;
2713 goto btree_open_out;
2714 }
2715 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
2716 sizeof(MemPage), flags, vfsFlags, pageReinit);
2717 if( rc==SQLITE_OK ){
2718 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
2719 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
2720 }
2721 if( rc!=SQLITE_OK ){
2722 goto btree_open_out;
2723 }
2724 pBt->openFlags = (u8)flags;
2725 pBt->db = db;
2726 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
2727 p->pBt = pBt;
2728
2729 pBt->pCursor = 0;
2730 pBt->pPage1 = 0;
2731 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
2732#if defined(SQLITE_SECURE_DELETE)
2733 pBt->btsFlags |= BTS_SECURE_DELETE;
2734#elif defined(SQLITE_FAST_SECURE_DELETE)
2735 pBt->btsFlags |= BTS_OVERWRITE;
2736#endif
2737 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
2738 ** determined by the 2-byte integer located at an offset of 16 bytes from
2739 ** the beginning of the database file. */
2740 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
2741 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
2742 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
2743 pBt->pageSize = 0;
2744#ifndef SQLITE_OMIT_AUTOVACUUM
2745 /* If the magic name ":memory:" will create an in-memory database, then
2746 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
2747 ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
2748 ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
2749 ** regular file-name. In this case the auto-vacuum applies as per normal.
2750 */
2751 if( zFilename && !isMemdb ){
2752 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
2753 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
2754 }
2755#endif
2756 nReserve = 0;
2757 }else{
2758 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
2759 ** determined by the one-byte unsigned integer found at an offset of 20
2760 ** into the database file header. */
2761 nReserve = zDbHeader[20];
2762 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
2763#ifndef SQLITE_OMIT_AUTOVACUUM
2764 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
2765 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
2766#endif
2767 }
2768 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2769 if( rc ) goto btree_open_out;
2770 pBt->usableSize = pBt->pageSize - nReserve;
2771 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
2772
2773#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2774 /* Add the new BtShared object to the linked list sharable BtShareds.
2775 */
2776 pBt->nRef = 1;
2777 if( p->sharable ){
2778 MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
2779 MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN);)
2780 if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
2781 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
2782 if( pBt->mutex==0 ){
2783 rc = SQLITE_NOMEM_BKPT;
2784 goto btree_open_out;
2785 }
2786 }
2787 sqlite3_mutex_enter(mutexShared);
2788 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
2789 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
2790 sqlite3_mutex_leave(mutexShared);
2791 }
2792#endif
2793 }
2794
2795#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
2796 /* If the new Btree uses a sharable pBtShared, then link the new
2797 ** Btree into the list of all sharable Btrees for the same connection.
2798 ** The list is kept in ascending order by pBt address.
2799 */
2800 if( p->sharable ){
2801 int i;
2802 Btree *pSib;
2803 for(i=0; i<db->nDb; i++){
2804 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
2805 while( pSib->pPrev ){ pSib = pSib->pPrev; }
2806 if( (uptr)p->pBt<(uptr)pSib->pBt ){
2807 p->pNext = pSib;
2808 p->pPrev = 0;
2809 pSib->pPrev = p;
2810 }else{
2811 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
2812 pSib = pSib->pNext;
2813 }
2814 p->pNext = pSib->pNext;
2815 p->pPrev = pSib;
2816 if( p->pNext ){
2817 p->pNext->pPrev = p;
2818 }
2819 pSib->pNext = p;
2820 }
2821 break;
2822 }
2823 }
2824 }
2825#endif
2826 *ppBtree = p;
2827
2828btree_open_out:
2829 if( rc!=SQLITE_OK ){
2830 if( pBt && pBt->pPager ){
2831 sqlite3PagerClose(pBt->pPager, 0);
2832 }
2833 sqlite3_free(pBt);
2834 sqlite3_free(p);
2835 *ppBtree = 0;
2836 }else{
2837 sqlite3_file *pFile;
2838
2839 /* If the B-Tree was successfully opened, set the pager-cache size to the
2840 ** default value. Except, when opening on an existing shared pager-cache,
2841 ** do not change the pager-cache size.
2842 */
2843 if( sqlite3BtreeSchema(p, 0, 0)==0 ){
2844 sqlite3BtreeSetCacheSize(p, SQLITE_DEFAULT_CACHE_SIZE);
2845 }
2846
2847 pFile = sqlite3PagerFile(pBt->pPager);
2848 if( pFile->pMethods ){
2849 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
2850 }
2851 }
2852 if( mutexOpen ){
2853 assert( sqlite3_mutex_held(mutexOpen) );
2854 sqlite3_mutex_leave(mutexOpen);
2855 }
2856 assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
2857 return rc;
2858}
2859
2860/*
2861** Decrement the BtShared.nRef counter. When it reaches zero,
2862** remove the BtShared structure from the sharing list. Return
2863** true if the BtShared.nRef counter reaches zero and return
2864** false if it is still positive.
2865*/
2866static int removeFromSharingList(BtShared *pBt){
2867#ifndef SQLITE_OMIT_SHARED_CACHE
2868 MUTEX_LOGIC( sqlite3_mutex *pMainMtx; )
2869 BtShared *pList;
2870 int removed = 0;
2871
2872 assert( sqlite3_mutex_notheld(pBt->mutex) );
2873 MUTEX_LOGIC( pMainMtx = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MAIN); )
2874 sqlite3_mutex_enter(pMainMtx);
2875 pBt->nRef--;
2876 if( pBt->nRef<=0 ){
2877 if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
2878 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
2879 }else{
2880 pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
2881 while( ALWAYS(pList) && pList->pNext!=pBt ){
2882 pList=pList->pNext;
2883 }
2884 if( ALWAYS(pList) ){
2885 pList->pNext = pBt->pNext;
2886 }
2887 }
2888 if( SQLITE_THREADSAFE ){
2889 sqlite3_mutex_free(pBt->mutex);
2890 }
2891 removed = 1;
2892 }
2893 sqlite3_mutex_leave(pMainMtx);
2894 return removed;
2895#else
2896 UNUSED_PARAMETER( pBt );
2897 return 1;
2898#endif
2899}
2900
2901/*
2902** Make sure pBt->pTmpSpace points to an allocation of
2903** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
2904** pointer.
2905*/
2906static SQLITE_NOINLINE int allocateTempSpace(BtShared *pBt){
2907 assert( pBt!=0 );
2908 assert( pBt->pTmpSpace==0 );
2909 /* This routine is called only by btreeCursor() when allocating the
2910 ** first write cursor for the BtShared object */
2911 assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
2912 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
2913 if( pBt->pTmpSpace==0 ){
2914 BtCursor *pCur = pBt->pCursor;
2915 pBt->pCursor = pCur->pNext; /* Unlink the cursor */
2916 memset(pCur, 0, sizeof(*pCur));
2917 return SQLITE_NOMEM_BKPT;
2918 }
2919
2920 /* One of the uses of pBt->pTmpSpace is to format cells before
2921 ** inserting them into a leaf page (function fillInCell()). If
2922 ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
2923 ** by the various routines that manipulate binary cells. Which
2924 ** can mean that fillInCell() only initializes the first 2 or 3
2925 ** bytes of pTmpSpace, but that the first 4 bytes are copied from
2926 ** it into a database page. This is not actually a problem, but it
2927 ** does cause a valgrind error when the 1 or 2 bytes of uninitialized
2928 ** data is passed to system call write(). So to avoid this error,
2929 ** zero the first 4 bytes of temp space here.
2930 **
2931 ** Also: Provide four bytes of initialized space before the
2932 ** beginning of pTmpSpace as an area available to prepend the
2933 ** left-child pointer to the beginning of a cell.
2934 */
2935 memset(pBt->pTmpSpace, 0, 8);
2936 pBt->pTmpSpace += 4;
2937 return SQLITE_OK;
2938}
2939
2940/*
2941** Free the pBt->pTmpSpace allocation
2942*/
2943static void freeTempSpace(BtShared *pBt){
2944 if( pBt->pTmpSpace ){
2945 pBt->pTmpSpace -= 4;
2946 sqlite3PageFree(pBt->pTmpSpace);
2947 pBt->pTmpSpace = 0;
2948 }
2949}
2950
2951/*
2952** Close an open database and invalidate all cursors.
2953*/
2954int sqlite3BtreeClose(Btree *p){
2955 BtShared *pBt = p->pBt;
2956
2957 /* Close all cursors opened via this handle. */
2958 assert( sqlite3_mutex_held(p->db->mutex) );
2959 sqlite3BtreeEnter(p);
2960
2961 /* Verify that no other cursors have this Btree open */
2962#ifdef SQLITE_DEBUG
2963 {
2964 BtCursor *pCur = pBt->pCursor;
2965 while( pCur ){
2966 BtCursor *pTmp = pCur;
2967 pCur = pCur->pNext;
2968 assert( pTmp->pBtree!=p );
2969
2970 }
2971 }
2972#endif
2973
2974 /* Rollback any active transaction and free the handle structure.
2975 ** The call to sqlite3BtreeRollback() drops any table-locks held by
2976 ** this handle.
2977 */
2978 sqlite3BtreeRollback(p, SQLITE_OK, 0);
2979 sqlite3BtreeLeave(p);
2980
2981 /* If there are still other outstanding references to the shared-btree
2982 ** structure, return now. The remainder of this procedure cleans
2983 ** up the shared-btree.
2984 */
2985 assert( p->wantToLock==0 && p->locked==0 );
2986 if( !p->sharable || removeFromSharingList(pBt) ){
2987 /* The pBt is no longer on the sharing list, so we can access
2988 ** it without having to hold the mutex.
2989 **
2990 ** Clean out and delete the BtShared object.
2991 */
2992 assert( !pBt->pCursor );
2993 sqlite3PagerClose(pBt->pPager, p->db);
2994 if( pBt->xFreeSchema && pBt->pSchema ){
2995 pBt->xFreeSchema(pBt->pSchema);
2996 }
2997 sqlite3DbFree(0, pBt->pSchema);
2998 freeTempSpace(pBt);
2999 sqlite3_free(pBt);
3000 }
3001
3002#ifndef SQLITE_OMIT_SHARED_CACHE
3003 assert( p->wantToLock==0 );
3004 assert( p->locked==0 );
3005 if( p->pPrev ) p->pPrev->pNext = p->pNext;
3006 if( p->pNext ) p->pNext->pPrev = p->pPrev;
3007#endif
3008
3009 sqlite3_free(p);
3010 return SQLITE_OK;
3011}
3012
3013/*
3014** Change the "soft" limit on the number of pages in the cache.
3015** Unused and unmodified pages will be recycled when the number of
3016** pages in the cache exceeds this soft limit. But the size of the
3017** cache is allowed to grow larger than this limit if it contains
3018** dirty pages or pages still in active use.
3019*/
3020int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
3021 BtShared *pBt = p->pBt;
3022 assert( sqlite3_mutex_held(p->db->mutex) );
3023 sqlite3BtreeEnter(p);
3024 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
3025 sqlite3BtreeLeave(p);
3026 return SQLITE_OK;
3027}
3028
3029/*
3030** Change the "spill" limit on the number of pages in the cache.
3031** If the number of pages exceeds this limit during a write transaction,
3032** the pager might attempt to "spill" pages to the journal early in
3033** order to free up memory.
3034**
3035** The value returned is the current spill size. If zero is passed
3036** as an argument, no changes are made to the spill size setting, so
3037** using mxPage of 0 is a way to query the current spill size.
3038*/
3039int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
3040 BtShared *pBt = p->pBt;
3041 int res;
3042 assert( sqlite3_mutex_held(p->db->mutex) );
3043 sqlite3BtreeEnter(p);
3044 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
3045 sqlite3BtreeLeave(p);
3046 return res;
3047}
3048
3049#if SQLITE_MAX_MMAP_SIZE>0
3050/*
3051** Change the limit on the amount of the database file that may be
3052** memory mapped.
3053*/
3054int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
3055 BtShared *pBt = p->pBt;
3056 assert( sqlite3_mutex_held(p->db->mutex) );
3057 sqlite3BtreeEnter(p);
3058 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
3059 sqlite3BtreeLeave(p);
3060 return SQLITE_OK;
3061}
3062#endif /* SQLITE_MAX_MMAP_SIZE>0 */
3063
3064/*
3065** Change the way data is synced to disk in order to increase or decrease
3066** how well the database resists damage due to OS crashes and power
3067** failures. Level 1 is the same as asynchronous (no syncs() occur and
3068** there is a high probability of damage) Level 2 is the default. There
3069** is a very low but non-zero probability of damage. Level 3 reduces the
3070** probability of damage to near zero but with a write performance reduction.
3071*/
3072#ifndef SQLITE_OMIT_PAGER_PRAGMAS
3073int sqlite3BtreeSetPagerFlags(
3074 Btree *p, /* The btree to set the safety level on */
3075 unsigned pgFlags /* Various PAGER_* flags */
3076){
3077 BtShared *pBt = p->pBt;
3078 assert( sqlite3_mutex_held(p->db->mutex) );
3079 sqlite3BtreeEnter(p);
3080 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
3081 sqlite3BtreeLeave(p);
3082 return SQLITE_OK;
3083}
3084#endif
3085
3086/*
3087** Change the default pages size and the number of reserved bytes per page.
3088** Or, if the page size has already been fixed, return SQLITE_READONLY
3089** without changing anything.
3090**
3091** The page size must be a power of 2 between 512 and 65536. If the page
3092** size supplied does not meet this constraint then the page size is not
3093** changed.
3094**
3095** Page sizes are constrained to be a power of two so that the region
3096** of the database file used for locking (beginning at PENDING_BYTE,
3097** the first byte past the 1GB boundary, 0x40000000) needs to occur
3098** at the beginning of a page.
3099**
3100** If parameter nReserve is less than zero, then the number of reserved
3101** bytes per page is left unchanged.
3102**
3103** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
3104** and autovacuum mode can no longer be changed.
3105*/
3106int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
3107 int rc = SQLITE_OK;
3108 int x;
3109 BtShared *pBt = p->pBt;
3110 assert( nReserve>=0 && nReserve<=255 );
3111 sqlite3BtreeEnter(p);
3112 pBt->nReserveWanted = (u8)nReserve;
3113 x = pBt->pageSize - pBt->usableSize;
3114 if( x==nReserve && (pageSize==0 || (u32)pageSize==pBt->pageSize) ){
3115 sqlite3BtreeLeave(p);
3116 return SQLITE_OK;
3117 }
3118 if( nReserve<x ) nReserve = x;
3119 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
3120 sqlite3BtreeLeave(p);
3121 return SQLITE_READONLY;
3122 }
3123 assert( nReserve>=0 && nReserve<=255 );
3124 if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
3125 ((pageSize-1)&pageSize)==0 ){
3126 assert( (pageSize & 7)==0 );
3127 assert( !pBt->pCursor );
3128 if( nReserve>32 && pageSize==512 ) pageSize = 1024;
3129 pBt->pageSize = (u32)pageSize;
3130 freeTempSpace(pBt);
3131 }
3132 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
3133 pBt->usableSize = pBt->pageSize - (u16)nReserve;
3134 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3135 sqlite3BtreeLeave(p);
3136 return rc;
3137}
3138
3139/*
3140** Return the currently defined page size
3141*/
3142int sqlite3BtreeGetPageSize(Btree *p){
3143 return p->pBt->pageSize;
3144}
3145
3146/*
3147** This function is similar to sqlite3BtreeGetReserve(), except that it
3148** may only be called if it is guaranteed that the b-tree mutex is already
3149** held.
3150**
3151** This is useful in one special case in the backup API code where it is
3152** known that the shared b-tree mutex is held, but the mutex on the
3153** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
3154** were to be called, it might collide with some other operation on the
3155** database handle that owns *p, causing undefined behavior.
3156*/
3157int sqlite3BtreeGetReserveNoMutex(Btree *p){
3158 int n;
3159 assert( sqlite3_mutex_held(p->pBt->mutex) );
3160 n = p->pBt->pageSize - p->pBt->usableSize;
3161 return n;
3162}
3163
3164/*
3165** Return the number of bytes of space at the end of every page that
3166** are intentionally left unused. This is the "reserved" space that is
3167** sometimes used by extensions.
3168**
3169** The value returned is the larger of the current reserve size and
3170** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
3171** The amount of reserve can only grow - never shrink.
3172*/
3173int sqlite3BtreeGetRequestedReserve(Btree *p){
3174 int n1, n2;
3175 sqlite3BtreeEnter(p);
3176 n1 = (int)p->pBt->nReserveWanted;
3177 n2 = sqlite3BtreeGetReserveNoMutex(p);
3178 sqlite3BtreeLeave(p);
3179 return n1>n2 ? n1 : n2;
3180}
3181
3182
3183/*
3184** Set the maximum page count for a database if mxPage is positive.
3185** No changes are made if mxPage is 0 or negative.
3186** Regardless of the value of mxPage, return the maximum page count.
3187*/
3188Pgno sqlite3BtreeMaxPageCount(Btree *p, Pgno mxPage){
3189 Pgno n;
3190 sqlite3BtreeEnter(p);
3191 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
3192 sqlite3BtreeLeave(p);
3193 return n;
3194}
3195
3196/*
3197** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
3198**
3199** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
3200** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
3201** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
3202** newFlag==(-1) No changes
3203**
3204** This routine acts as a query if newFlag is less than zero
3205**
3206** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
3207** freelist leaf pages are not written back to the database. Thus in-page
3208** deleted content is cleared, but freelist deleted content is not.
3209**
3210** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
3211** that freelist leaf pages are written back into the database, increasing
3212** the amount of disk I/O.
3213*/
3214int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
3215 int b;
3216 if( p==0 ) return 0;
3217 sqlite3BtreeEnter(p);
3218 assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
3219 assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
3220 if( newFlag>=0 ){
3221 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
3222 p->pBt->btsFlags |= (u16)(BTS_SECURE_DELETE*newFlag);
3223 }
3224 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
3225 sqlite3BtreeLeave(p);
3226 return b;
3227}
3228
3229/*
3230** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
3231** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
3232** is disabled. The default value for the auto-vacuum property is
3233** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
3234*/
3235int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
3236#ifdef SQLITE_OMIT_AUTOVACUUM
3237 return SQLITE_READONLY;
3238#else
3239 BtShared *pBt = p->pBt;
3240 int rc = SQLITE_OK;
3241 u8 av = (u8)autoVacuum;
3242
3243 sqlite3BtreeEnter(p);
3244 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
3245 rc = SQLITE_READONLY;
3246 }else{
3247 pBt->autoVacuum = av ?1:0;
3248 pBt->incrVacuum = av==2 ?1:0;
3249 }
3250 sqlite3BtreeLeave(p);
3251 return rc;
3252#endif
3253}
3254
3255/*
3256** Return the value of the 'auto-vacuum' property. If auto-vacuum is
3257** enabled 1 is returned. Otherwise 0.
3258*/
3259int sqlite3BtreeGetAutoVacuum(Btree *p){
3260#ifdef SQLITE_OMIT_AUTOVACUUM
3261 return BTREE_AUTOVACUUM_NONE;
3262#else
3263 int rc;
3264 sqlite3BtreeEnter(p);
3265 rc = (
3266 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
3267 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
3268 BTREE_AUTOVACUUM_INCR
3269 );
3270 sqlite3BtreeLeave(p);
3271 return rc;
3272#endif
3273}
3274
3275/*
3276** If the user has not set the safety-level for this database connection
3277** using "PRAGMA synchronous", and if the safety-level is not already
3278** set to the value passed to this function as the second parameter,
3279** set it so.
3280*/
3281#if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
3282 && !defined(SQLITE_OMIT_WAL)
3283static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
3284 sqlite3 *db;
3285 Db *pDb;
3286 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
3287 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
3288 if( pDb->bSyncSet==0
3289 && pDb->safety_level!=safety_level
3290 && pDb!=&db->aDb[1]
3291 ){
3292 pDb->safety_level = safety_level;
3293 sqlite3PagerSetFlags(pBt->pPager,
3294 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
3295 }
3296 }
3297}
3298#else
3299# define setDefaultSyncFlag(pBt,safety_level)
3300#endif
3301
3302/* Forward declaration */
3303static int newDatabase(BtShared*);
3304
3305
3306/*
3307** Get a reference to pPage1 of the database file. This will
3308** also acquire a readlock on that file.
3309**
3310** SQLITE_OK is returned on success. If the file is not a
3311** well-formed database file, then SQLITE_CORRUPT is returned.
3312** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
3313** is returned if we run out of memory.
3314*/
3315static int lockBtree(BtShared *pBt){
3316 int rc; /* Result code from subfunctions */
3317 MemPage *pPage1; /* Page 1 of the database file */
3318 u32 nPage; /* Number of pages in the database */
3319 u32 nPageFile = 0; /* Number of pages in the database file */
3320
3321 assert( sqlite3_mutex_held(pBt->mutex) );
3322 assert( pBt->pPage1==0 );
3323 rc = sqlite3PagerSharedLock(pBt->pPager);
3324 if( rc!=SQLITE_OK ) return rc;
3325 rc = btreeGetPage(pBt, 1, &pPage1, 0);
3326 if( rc!=SQLITE_OK ) return rc;
3327
3328 /* Do some checking to help insure the file we opened really is
3329 ** a valid database file.
3330 */
3331 nPage = get4byte(28+(u8*)pPage1->aData);
3332 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
3333 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
3334 nPage = nPageFile;
3335 }
3336 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
3337 nPage = 0;
3338 }
3339 if( nPage>0 ){
3340 u32 pageSize;
3341 u32 usableSize;
3342 u8 *page1 = pPage1->aData;
3343 rc = SQLITE_NOTADB;
3344 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
3345 ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
3346 ** 61 74 20 33 00. */
3347 if( memcmp(page1, zMagicHeader, 16)!=0 ){
3348 goto page1_init_failed;
3349 }
3350
3351#ifdef SQLITE_OMIT_WAL
3352 if( page1[18]>1 ){
3353 pBt->btsFlags |= BTS_READ_ONLY;
3354 }
3355 if( page1[19]>1 ){
3356 goto page1_init_failed;
3357 }
3358#else
3359 if( page1[18]>2 ){
3360 pBt->btsFlags |= BTS_READ_ONLY;
3361 }
3362 if( page1[19]>2 ){
3363 goto page1_init_failed;
3364 }
3365
3366 /* If the read version is set to 2, this database should be accessed
3367 ** in WAL mode. If the log is not already open, open it now. Then
3368 ** return SQLITE_OK and return without populating BtShared.pPage1.
3369 ** The caller detects this and calls this function again. This is
3370 ** required as the version of page 1 currently in the page1 buffer
3371 ** may not be the latest version - there may be a newer one in the log
3372 ** file.
3373 */
3374 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
3375 int isOpen = 0;
3376 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
3377 if( rc!=SQLITE_OK ){
3378 goto page1_init_failed;
3379 }else{
3380 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
3381 if( isOpen==0 ){
3382 releasePageOne(pPage1);
3383 return SQLITE_OK;
3384 }
3385 }
3386 rc = SQLITE_NOTADB;
3387 }else{
3388 setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
3389 }
3390#endif
3391
3392 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
3393 ** fractions and the leaf payload fraction values must be 64, 32, and 32.
3394 **
3395 ** The original design allowed these amounts to vary, but as of
3396 ** version 3.6.0, we require them to be fixed.
3397 */
3398 if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
3399 goto page1_init_failed;
3400 }
3401 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
3402 ** determined by the 2-byte integer located at an offset of 16 bytes from
3403 ** the beginning of the database file. */
3404 pageSize = (page1[16]<<8) | (page1[17]<<16);
3405 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
3406 ** between 512 and 65536 inclusive. */
3407 if( ((pageSize-1)&pageSize)!=0
3408 || pageSize>SQLITE_MAX_PAGE_SIZE
3409 || pageSize<=256
3410 ){
3411 goto page1_init_failed;
3412 }
3413 assert( (pageSize & 7)==0 );
3414 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
3415 ** integer at offset 20 is the number of bytes of space at the end of
3416 ** each page to reserve for extensions.
3417 **
3418 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
3419 ** determined by the one-byte unsigned integer found at an offset of 20
3420 ** into the database file header. */
3421 usableSize = pageSize - page1[20];
3422 if( (u32)pageSize!=pBt->pageSize ){
3423 /* After reading the first page of the database assuming a page size
3424 ** of BtShared.pageSize, we have discovered that the page-size is
3425 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
3426 ** zero and return SQLITE_OK. The caller will call this function
3427 ** again with the correct page-size.
3428 */
3429 releasePageOne(pPage1);
3430 pBt->usableSize = usableSize;
3431 pBt->pageSize = pageSize;
3432 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3433 freeTempSpace(pBt);
3434 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
3435 pageSize-usableSize);
3436 return rc;
3437 }
3438 if( nPage>nPageFile ){
3439 if( sqlite3WritableSchema(pBt->db)==0 ){
3440 rc = SQLITE_CORRUPT_BKPT;
3441 goto page1_init_failed;
3442 }else{
3443 nPage = nPageFile;
3444 }
3445 }
3446 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
3447 ** be less than 480. In other words, if the page size is 512, then the
3448 ** reserved space size cannot exceed 32. */
3449 if( usableSize<480 ){
3450 goto page1_init_failed;
3451 }
3452 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3453 pBt->pageSize = pageSize;
3454 pBt->usableSize = usableSize;
3455#ifndef SQLITE_OMIT_AUTOVACUUM
3456 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
3457 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
3458#endif
3459 }
3460
3461 /* maxLocal is the maximum amount of payload to store locally for
3462 ** a cell. Make sure it is small enough so that at least minFanout
3463 ** cells can will fit on one page. We assume a 10-byte page header.
3464 ** Besides the payload, the cell must store:
3465 ** 2-byte pointer to the cell
3466 ** 4-byte child pointer
3467 ** 9-byte nKey value
3468 ** 4-byte nData value
3469 ** 4-byte overflow page pointer
3470 ** So a cell consists of a 2-byte pointer, a header which is as much as
3471 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
3472 ** page pointer.
3473 */
3474 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
3475 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
3476 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
3477 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
3478 if( pBt->maxLocal>127 ){
3479 pBt->max1bytePayload = 127;
3480 }else{
3481 pBt->max1bytePayload = (u8)pBt->maxLocal;
3482 }
3483 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
3484 pBt->pPage1 = pPage1;
3485 pBt->nPage = nPage;
3486 return SQLITE_OK;
3487
3488page1_init_failed:
3489 releasePageOne(pPage1);
3490 pBt->pPage1 = 0;
3491 return rc;
3492}
3493
3494#ifndef NDEBUG
3495/*
3496** Return the number of cursors open on pBt. This is for use
3497** in assert() expressions, so it is only compiled if NDEBUG is not
3498** defined.
3499**
3500** Only write cursors are counted if wrOnly is true. If wrOnly is
3501** false then all cursors are counted.
3502**
3503** For the purposes of this routine, a cursor is any cursor that
3504** is capable of reading or writing to the database. Cursors that
3505** have been tripped into the CURSOR_FAULT state are not counted.
3506*/
3507static int countValidCursors(BtShared *pBt, int wrOnly){
3508 BtCursor *pCur;
3509 int r = 0;
3510 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
3511 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
3512 && pCur->eState!=CURSOR_FAULT ) r++;
3513 }
3514 return r;
3515}
3516#endif
3517
3518/*
3519** If there are no outstanding cursors and we are not in the middle
3520** of a transaction but there is a read lock on the database, then
3521** this routine unrefs the first page of the database file which
3522** has the effect of releasing the read lock.
3523**
3524** If there is a transaction in progress, this routine is a no-op.
3525*/
3526static void unlockBtreeIfUnused(BtShared *pBt){
3527 assert( sqlite3_mutex_held(pBt->mutex) );
3528 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
3529 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
3530 MemPage *pPage1 = pBt->pPage1;
3531 assert( pPage1->aData );
3532 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
3533 pBt->pPage1 = 0;
3534 releasePageOne(pPage1);
3535 }
3536}
3537
3538/*
3539** If pBt points to an empty file then convert that empty file
3540** into a new empty database by initializing the first page of
3541** the database.
3542*/
3543static int newDatabase(BtShared *pBt){
3544 MemPage *pP1;
3545 unsigned char *data;
3546 int rc;
3547
3548 assert( sqlite3_mutex_held(pBt->mutex) );
3549 if( pBt->nPage>0 ){
3550 return SQLITE_OK;
3551 }
3552 pP1 = pBt->pPage1;
3553 assert( pP1!=0 );
3554 data = pP1->aData;
3555 rc = sqlite3PagerWrite(pP1->pDbPage);
3556 if( rc ) return rc;
3557 memcpy(data, zMagicHeader, sizeof(zMagicHeader));
3558 assert( sizeof(zMagicHeader)==16 );
3559 data[16] = (u8)((pBt->pageSize>>8)&0xff);
3560 data[17] = (u8)((pBt->pageSize>>16)&0xff);
3561 data[18] = 1;
3562 data[19] = 1;
3563 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
3564 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
3565 data[21] = 64;
3566 data[22] = 32;
3567 data[23] = 32;
3568 memset(&data[24], 0, 100-24);
3569 zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
3570 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
3571#ifndef SQLITE_OMIT_AUTOVACUUM
3572 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
3573 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
3574 put4byte(&data[36 + 4*4], pBt->autoVacuum);
3575 put4byte(&data[36 + 7*4], pBt->incrVacuum);
3576#endif
3577 pBt->nPage = 1;
3578 data[31] = 1;
3579 return SQLITE_OK;
3580}
3581
3582/*
3583** Initialize the first page of the database file (creating a database
3584** consisting of a single page and no schema objects). Return SQLITE_OK
3585** if successful, or an SQLite error code otherwise.
3586*/
3587int sqlite3BtreeNewDb(Btree *p){
3588 int rc;
3589 sqlite3BtreeEnter(p);
3590 p->pBt->nPage = 0;
3591 rc = newDatabase(p->pBt);
3592 sqlite3BtreeLeave(p);
3593 return rc;
3594}
3595
3596/*
3597** Attempt to start a new transaction. A write-transaction
3598** is started if the second argument is nonzero, otherwise a read-
3599** transaction. If the second argument is 2 or more and exclusive
3600** transaction is started, meaning that no other process is allowed
3601** to access the database. A preexisting transaction may not be
3602** upgraded to exclusive by calling this routine a second time - the
3603** exclusivity flag only works for a new transaction.
3604**
3605** A write-transaction must be started before attempting any
3606** changes to the database. None of the following routines
3607** will work unless a transaction is started first:
3608**
3609** sqlite3BtreeCreateTable()
3610** sqlite3BtreeCreateIndex()
3611** sqlite3BtreeClearTable()
3612** sqlite3BtreeDropTable()
3613** sqlite3BtreeInsert()
3614** sqlite3BtreeDelete()
3615** sqlite3BtreeUpdateMeta()
3616**
3617** If an initial attempt to acquire the lock fails because of lock contention
3618** and the database was previously unlocked, then invoke the busy handler
3619** if there is one. But if there was previously a read-lock, do not
3620** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
3621** returned when there is already a read-lock in order to avoid a deadlock.
3622**
3623** Suppose there are two processes A and B. A has a read lock and B has
3624** a reserved lock. B tries to promote to exclusive but is blocked because
3625** of A's read lock. A tries to promote to reserved but is blocked by B.
3626** One or the other of the two processes must give way or there can be
3627** no progress. By returning SQLITE_BUSY and not invoking the busy callback
3628** when A already has a read lock, we encourage A to give up and let B
3629** proceed.
3630*/
3631static SQLITE_NOINLINE int btreeBeginTrans(
3632 Btree *p, /* The btree in which to start the transaction */
3633 int wrflag, /* True to start a write transaction */
3634 int *pSchemaVersion /* Put schema version number here, if not NULL */
3635){
3636 BtShared *pBt = p->pBt;
3637 Pager *pPager = pBt->pPager;
3638 int rc = SQLITE_OK;
3639
3640 sqlite3BtreeEnter(p);
3641 btreeIntegrity(p);
3642
3643 /* If the btree is already in a write-transaction, or it
3644 ** is already in a read-transaction and a read-transaction
3645 ** is requested, this is a no-op.
3646 */
3647 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
3648 goto trans_begun;
3649 }
3650 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
3651
3652 if( (p->db->flags & SQLITE_ResetDatabase)
3653 && sqlite3PagerIsreadonly(pPager)==0
3654 ){
3655 pBt->btsFlags &= ~BTS_READ_ONLY;
3656 }
3657
3658 /* Write transactions are not possible on a read-only database */
3659 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
3660 rc = SQLITE_READONLY;
3661 goto trans_begun;
3662 }
3663
3664#ifndef SQLITE_OMIT_SHARED_CACHE
3665 {
3666 sqlite3 *pBlock = 0;
3667 /* If another database handle has already opened a write transaction
3668 ** on this shared-btree structure and a second write transaction is
3669 ** requested, return SQLITE_LOCKED.
3670 */
3671 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
3672 || (pBt->btsFlags & BTS_PENDING)!=0
3673 ){
3674 pBlock = pBt->pWriter->db;
3675 }else if( wrflag>1 ){
3676 BtLock *pIter;
3677 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
3678 if( pIter->pBtree!=p ){
3679 pBlock = pIter->pBtree->db;
3680 break;
3681 }
3682 }
3683 }
3684 if( pBlock ){
3685 sqlite3ConnectionBlocked(p->db, pBlock);
3686 rc = SQLITE_LOCKED_SHAREDCACHE;
3687 goto trans_begun;
3688 }
3689 }
3690#endif
3691
3692 /* Any read-only or read-write transaction implies a read-lock on
3693 ** page 1. So if some other shared-cache client already has a write-lock
3694 ** on page 1, the transaction cannot be opened. */
3695 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
3696 if( SQLITE_OK!=rc ) goto trans_begun;
3697
3698 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
3699 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
3700 do {
3701 sqlite3PagerWalDb(pPager, p->db);
3702
3703#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3704 /* If transitioning from no transaction directly to a write transaction,
3705 ** block for the WRITER lock first if possible. */
3706 if( pBt->pPage1==0 && wrflag ){
3707 assert( pBt->inTransaction==TRANS_NONE );
3708 rc = sqlite3PagerWalWriteLock(pPager, 1);
3709 if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
3710 }
3711#endif
3712
3713#ifdef SQLITE_EXPERIMENTAL_PRAGMA_20251114
3714 /* If both a read and write transaction will be opened by this call,
3715 ** then issue a file-control as if the following pragma command had
3716 ** been evaluated:
3717 **
3718 ** PRAGMA experimental_pragma_20251114 = 1|2
3719 **
3720 ** where the RHS is "1" if wrflag is 1 (RESERVED lock), or "2" if wrflag
3721 ** is 2 (EXCLUSIVE lock). Ignore any result or error returned by the VFS.
3722 **
3723 ** WARNING: This code will likely remain part of SQLite only temporarily -
3724 ** it exists to allow users to experiment with certain types of blocking
3725 ** locks in custom VFS implementations. It MAY BE REMOVED AT ANY TIME. */
3726 if( pBt->pPage1==0 && wrflag ){
3727 sqlite3_file *fd = sqlite3PagerFile(pPager);
3728 char *aFcntl[3] = {0,0,0};
3729 aFcntl[1] = "experimental_pragma_20251114";
3730 assert( wrflag==1 || wrflag==2 );
3731 aFcntl[2] = (wrflag==1 ? "1" : "2");
3732 sqlite3OsFileControlHint(fd, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
3733 sqlite3_free(aFcntl[0]);
3734 }
3735#endif
3736
3737 /* Call lockBtree() until either pBt->pPage1 is populated or
3738 ** lockBtree() returns something other than SQLITE_OK. lockBtree()
3739 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
3740 ** reading page 1 it discovers that the page-size of the database
3741 ** file is not pBt->pageSize. In this case lockBtree() will update
3742 ** pBt->pageSize to the page-size of the file on disk.
3743 */
3744 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
3745
3746 if( rc==SQLITE_OK && wrflag ){
3747 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
3748 rc = SQLITE_READONLY;
3749 }else{
3750 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
3751 if( rc==SQLITE_OK ){
3752 rc = newDatabase(pBt);
3753 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
3754 /* if there was no transaction opened when this function was
3755 ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
3756 ** code to SQLITE_BUSY. */
3757 rc = SQLITE_BUSY;
3758 }
3759 }
3760 }
3761
3762 if( rc!=SQLITE_OK ){
3763 (void)sqlite3PagerWalWriteLock(pPager, 0);
3764 unlockBtreeIfUnused(pBt);
3765 }
3766#if defined(SQLITE_ENABLE_SETLK_TIMEOUT)
3767 if( rc==SQLITE_BUSY_TIMEOUT ){
3768 /* If a blocking lock timed out, break out of the loop here so that
3769 ** the busy-handler is not invoked. */
3770 break;
3771 }
3772#endif
3773 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
3774 btreeInvokeBusyHandler(pBt) );
3775 sqlite3PagerWalDb(pPager, 0);
3776#ifdef SQLITE_ENABLE_SETLK_TIMEOUT
3777 if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
3778#endif
3779
3780 if( rc==SQLITE_OK ){
3781 if( p->inTrans==TRANS_NONE ){
3782 pBt->nTransaction++;
3783#ifndef SQLITE_OMIT_SHARED_CACHE
3784 if( p->sharable ){
3785 assert( p->lock.pBtree==p && p->lock.iTable==1 );
3786 p->lock.eLock = READ_LOCK;
3787 p->lock.pNext = pBt->pLock;
3788 pBt->pLock = &p->lock;
3789 }
3790#endif
3791 }
3792 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
3793 if( p->inTrans>pBt->inTransaction ){
3794 pBt->inTransaction = p->inTrans;
3795 }
3796 if( wrflag ){
3797 MemPage *pPage1 = pBt->pPage1;
3798#ifndef SQLITE_OMIT_SHARED_CACHE
3799 assert( !pBt->pWriter );
3800 pBt->pWriter = p;
3801 pBt->btsFlags &= ~BTS_EXCLUSIVE;
3802 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
3803#endif
3804
3805 /* If the db-size header field is incorrect (as it may be if an old
3806 ** client has been writing the database file), update it now. Doing
3807 ** this sooner rather than later means the database size can safely
3808 ** re-read the database size from page 1 if a savepoint or transaction
3809 ** rollback occurs within the transaction.
3810 */
3811 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
3812 rc = sqlite3PagerWrite(pPage1->pDbPage);
3813 if( rc==SQLITE_OK ){
3814 put4byte(&pPage1->aData[28], pBt->nPage);
3815 }
3816 }
3817 }
3818 }
3819
3820trans_begun:
3821 if( rc==SQLITE_OK ){
3822 if( pSchemaVersion ){
3823 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3824 }
3825 if( wrflag ){
3826 /* This call makes sure that the pager has the correct number of
3827 ** open savepoints. If the second parameter is greater than 0 and
3828 ** the sub-journal is not already open, then it will be opened here.
3829 */
3830 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
3831 }
3832 }
3833
3834 btreeIntegrity(p);
3835 sqlite3BtreeLeave(p);
3836 return rc;
3837}
3838int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
3839 BtShared *pBt;
3840 if( p->sharable
3841 || p->inTrans==TRANS_NONE
3842 || (p->inTrans==TRANS_READ && wrflag!=0)
3843 ){
3844 return btreeBeginTrans(p,wrflag,pSchemaVersion);
3845 }
3846 pBt = p->pBt;
3847 if( pSchemaVersion ){
3848 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
3849 }
3850 if( wrflag ){
3851 /* This call makes sure that the pager has the correct number of
3852 ** open savepoints. If the second parameter is greater than 0 and
3853 ** the sub-journal is not already open, then it will be opened here.
3854 */
3855 return sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
3856 }else{
3857 return SQLITE_OK;
3858 }
3859}
3860
3861#ifndef SQLITE_OMIT_AUTOVACUUM
3862
3863/*
3864** Set the pointer-map entries for all children of page pPage. Also, if
3865** pPage contains cells that point to overflow pages, set the pointer
3866** map entries for the overflow pages as well.
3867*/
3868static int setChildPtrmaps(MemPage *pPage){
3869 int i; /* Counter variable */
3870 int nCell; /* Number of cells in page pPage */
3871 int rc; /* Return code */
3872 BtShared *pBt = pPage->pBt;
3873 Pgno pgno = pPage->pgno;
3874
3875 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3876 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3877 if( rc!=SQLITE_OK ) return rc;
3878 nCell = pPage->nCell;
3879
3880 for(i=0; i<nCell; i++){
3881 u8 *pCell = findCell(pPage, i);
3882
3883 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
3884
3885 if( !pPage->leaf ){
3886 Pgno childPgno = get4byte(pCell);
3887 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3888 }
3889 }
3890
3891 if( !pPage->leaf ){
3892 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
3893 ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
3894 }
3895
3896 return rc;
3897}
3898
3899/*
3900** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
3901** that it points to iTo. Parameter eType describes the type of pointer to
3902** be modified, as follows:
3903**
3904** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
3905** page of pPage.
3906**
3907** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
3908** page pointed to by one of the cells on pPage.
3909**
3910** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
3911** overflow page in the list.
3912*/
3913static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
3914 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
3915 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
3916 if( eType==PTRMAP_OVERFLOW2 ){
3917 /* The pointer is always the first 4 bytes of the page in this case. */
3918 if( get4byte(pPage->aData)!=iFrom ){
3919 return SQLITE_CORRUPT_PAGE(pPage);
3920 }
3921 put4byte(pPage->aData, iTo);
3922 }else{
3923 int i;
3924 int nCell;
3925 int rc;
3926
3927 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
3928 if( rc ) return rc;
3929 nCell = pPage->nCell;
3930
3931 for(i=0; i<nCell; i++){
3932 u8 *pCell = findCell(pPage, i);
3933 if( eType==PTRMAP_OVERFLOW1 ){
3934 CellInfo info;
3935 pPage->xParseCell(pPage, pCell, &info);
3936 if( info.nLocal<info.nPayload ){
3937 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
3938 return SQLITE_CORRUPT_PAGE(pPage);
3939 }
3940 if( iFrom==get4byte(pCell+info.nSize-4) ){
3941 put4byte(pCell+info.nSize-4, iTo);
3942 break;
3943 }
3944 }
3945 }else{
3946 if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
3947 return SQLITE_CORRUPT_PAGE(pPage);
3948 }
3949 if( get4byte(pCell)==iFrom ){
3950 put4byte(pCell, iTo);
3951 break;
3952 }
3953 }
3954 }
3955
3956 if( i==nCell ){
3957 if( eType!=PTRMAP_BTREE ||
3958 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
3959 return SQLITE_CORRUPT_PAGE(pPage);
3960 }
3961 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
3962 }
3963 }
3964 return SQLITE_OK;
3965}
3966
3967
3968/*
3969** Move the open database page pDbPage to location iFreePage in the
3970** database. The pDbPage reference remains valid.
3971**
3972** The isCommit flag indicates that there is no need to remember that
3973** the journal needs to be sync()ed before database page pDbPage->pgno
3974** can be written to. The caller has already promised not to write to that
3975** page.
3976*/
3977static int relocatePage(
3978 BtShared *pBt, /* Btree */
3979 MemPage *pDbPage, /* Open page to move */
3980 u8 eType, /* Pointer map 'type' entry for pDbPage */
3981 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
3982 Pgno iFreePage, /* The location to move pDbPage to */
3983 int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
3984){
3985 MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
3986 Pgno iDbPage = pDbPage->pgno;
3987 Pager *pPager = pBt->pPager;
3988 int rc;
3989
3990 assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
3991 eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
3992 assert( sqlite3_mutex_held(pBt->mutex) );
3993 assert( pDbPage->pBt==pBt );
3994 if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
3995
3996 /* Move page iDbPage from its current location to page number iFreePage */
3997 TRACE(("AUTOVACUUM: Moving %u to free page %u (ptr page %u type %u)\n",
3998 iDbPage, iFreePage, iPtrPage, eType));
3999 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
4000 if( rc!=SQLITE_OK ){
4001 return rc;
4002 }
4003 pDbPage->pgno = iFreePage;
4004
4005 /* If pDbPage was a btree-page, then it may have child pages and/or cells
4006 ** that point to overflow pages. The pointer map entries for all these
4007 ** pages need to be changed.
4008 **
4009 ** If pDbPage is an overflow page, then the first 4 bytes may store a
4010 ** pointer to a subsequent overflow page. If this is the case, then
4011 ** the pointer map needs to be updated for the subsequent overflow page.
4012 */
4013 if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
4014 rc = setChildPtrmaps(pDbPage);
4015 if( rc!=SQLITE_OK ){
4016 return rc;
4017 }
4018 }else{
4019 Pgno nextOvfl = get4byte(pDbPage->aData);
4020 if( nextOvfl!=0 ){
4021 ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
4022 if( rc!=SQLITE_OK ){
4023 return rc;
4024 }
4025 }
4026 }
4027
4028 /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
4029 ** that it points at iFreePage. Also fix the pointer map entry for
4030 ** iPtrPage.
4031 */
4032 if( eType!=PTRMAP_ROOTPAGE ){
4033 rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
4034 if( rc!=SQLITE_OK ){
4035 return rc;
4036 }
4037 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
4038 if( rc!=SQLITE_OK ){
4039 releasePage(pPtrPage);
4040 return rc;
4041 }
4042 rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
4043 releasePage(pPtrPage);
4044 if( rc==SQLITE_OK ){
4045 ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
4046 }
4047 }
4048 return rc;
4049}
4050
4051/* Forward declaration required by incrVacuumStep(). */
4052static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
4053
4054/*
4055** Perform a single step of an incremental-vacuum. If successful, return
4056** SQLITE_OK. If there is no work to do (and therefore no point in
4057** calling this function again), return SQLITE_DONE. Or, if an error
4058** occurs, return some other error code.
4059**
4060** More specifically, this function attempts to re-organize the database so
4061** that the last page of the file currently in use is no longer in use.
4062**
4063** Parameter nFin is the number of pages that this database would contain
4064** were this function called until it returns SQLITE_DONE.
4065**
4066** If the bCommit parameter is non-zero, this function assumes that the
4067** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
4068** or an error. bCommit is passed true for an auto-vacuum-on-commit
4069** operation, or false for an incremental vacuum.
4070*/
4071static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
4072 Pgno nFreeList; /* Number of pages still on the free-list */
4073 int rc;
4074
4075 assert( sqlite3_mutex_held(pBt->mutex) );
4076 assert( iLastPg>nFin );
4077
4078 if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
4079 u8 eType;
4080 Pgno iPtrPage;
4081
4082 nFreeList = get4byte(&pBt->pPage1->aData[36]);
4083 if( nFreeList==0 ){
4084 return SQLITE_DONE;
4085 }
4086
4087 rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
4088 if( rc!=SQLITE_OK ){
4089 return rc;
4090 }
4091 if( eType==PTRMAP_ROOTPAGE ){
4092 return SQLITE_CORRUPT_BKPT;
4093 }
4094
4095 if( eType==PTRMAP_FREEPAGE ){
4096 if( bCommit==0 ){
4097 /* Remove the page from the files free-list. This is not required
4098 ** if bCommit is non-zero. In that case, the free-list will be
4099 ** truncated to zero after this function returns, so it doesn't
4100 ** matter if it still contains some garbage entries.
4101 */
4102 Pgno iFreePg;
4103 MemPage *pFreePg;
4104 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
4105 if( rc!=SQLITE_OK ){
4106 return rc;
4107 }
4108 assert( iFreePg==iLastPg );
4109 releasePage(pFreePg);
4110 }
4111 } else {
4112 Pgno iFreePg; /* Index of free page to move pLastPg to */
4113 MemPage *pLastPg;
4114 u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
4115 Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
4116
4117 rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
4118 if( rc!=SQLITE_OK ){
4119 return rc;
4120 }
4121
4122 /* If bCommit is zero, this loop runs exactly once and page pLastPg
4123 ** is swapped with the first free page pulled off the free list.
4124 **
4125 ** On the other hand, if bCommit is greater than zero, then keep
4126 ** looping until a free-page located within the first nFin pages
4127 ** of the file is found.
4128 */
4129 if( bCommit==0 ){
4130 eMode = BTALLOC_LE;
4131 iNear = nFin;
4132 }
4133 do {
4134 MemPage *pFreePg;
4135 Pgno dbSize = btreePagecount(pBt);
4136 rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
4137 if( rc!=SQLITE_OK ){
4138 releasePage(pLastPg);
4139 return rc;
4140 }
4141 releasePage(pFreePg);
4142 if( iFreePg>dbSize ){
4143 releasePage(pLastPg);
4144 return SQLITE_CORRUPT_BKPT;
4145 }
4146 }while( bCommit && iFreePg>nFin );
4147 assert( iFreePg<iLastPg );
4148
4149 rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
4150 releasePage(pLastPg);
4151 if( rc!=SQLITE_OK ){
4152 return rc;
4153 }
4154 }
4155 }
4156
4157 if( bCommit==0 ){
4158 do {
4159 iLastPg--;
4160 }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
4161 pBt->bDoTruncate = 1;
4162 pBt->nPage = iLastPg;
4163 }
4164 return SQLITE_OK;
4165}
4166
4167/*
4168** The database opened by the first argument is an auto-vacuum database
4169** nOrig pages in size containing nFree free pages. Return the expected
4170** size of the database in pages following an auto-vacuum operation.
4171*/
4172static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
4173 int nEntry; /* Number of entries on one ptrmap page */
4174 Pgno nPtrmap; /* Number of PtrMap pages to be freed */
4175 Pgno nFin; /* Return value */
4176
4177 nEntry = pBt->usableSize/5;
4178 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
4179 nFin = nOrig - nFree - nPtrmap;
4180 if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
4181 nFin--;
4182 }
4183 while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
4184 nFin--;
4185 }
4186
4187 return nFin;
4188}
4189
4190/*
4191** A write-transaction must be opened before calling this function.
4192** It performs a single unit of work towards an incremental vacuum.
4193**
4194** If the incremental vacuum is finished after this function has run,
4195** SQLITE_DONE is returned. If it is not finished, but no error occurred,
4196** SQLITE_OK is returned. Otherwise an SQLite error code.
4197*/
4198int sqlite3BtreeIncrVacuum(Btree *p){
4199 int rc;
4200 BtShared *pBt = p->pBt;
4201
4202 sqlite3BtreeEnter(p);
4203 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
4204 if( !pBt->autoVacuum ){
4205 rc = SQLITE_DONE;
4206 }else{
4207 Pgno nOrig = btreePagecount(pBt);
4208 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
4209 Pgno nFin = finalDbSize(pBt, nOrig, nFree);
4210
4211 if( nOrig<nFin || nFree>=nOrig ){
4212 rc = SQLITE_CORRUPT_BKPT;
4213 }else if( nFree>0 ){
4214 rc = saveAllCursors(pBt, 0, 0);
4215 if( rc==SQLITE_OK ){
4216 invalidateAllOverflowCache(pBt);
4217 rc = incrVacuumStep(pBt, nFin, nOrig, 0);
4218 }
4219 if( rc==SQLITE_OK ){
4220 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4221 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
4222 }
4223 }else{
4224 rc = SQLITE_DONE;
4225 }
4226 }
4227 sqlite3BtreeLeave(p);
4228 return rc;
4229}
4230
4231/*
4232** This routine is called prior to sqlite3PagerCommit when a transaction
4233** is committed for an auto-vacuum database.
4234*/
4235static int autoVacuumCommit(Btree *p){
4236 int rc = SQLITE_OK;
4237 Pager *pPager;
4238 BtShared *pBt;
4239 sqlite3 *db;
4240 VVA_ONLY( int nRef );
4241
4242 assert( p!=0 );
4243 pBt = p->pBt;
4244 pPager = pBt->pPager;
4245 VVA_ONLY( nRef = sqlite3PagerRefcount(pPager); )
4246
4247 assert( sqlite3_mutex_held(pBt->mutex) );
4248 invalidateAllOverflowCache(pBt);
4249 assert(pBt->autoVacuum);
4250 if( !pBt->incrVacuum ){
4251 Pgno nFin; /* Number of pages in database after autovacuuming */
4252 Pgno nFree; /* Number of pages on the freelist initially */
4253 Pgno nVac; /* Number of pages to vacuum */
4254 Pgno iFree; /* The next page to be freed */
4255 Pgno nOrig; /* Database size before freeing */
4256
4257 nOrig = btreePagecount(pBt);
4258 if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
4259 /* It is not possible to create a database for which the final page
4260 ** is either a pointer-map page or the pending-byte page. If one
4261 ** is encountered, this indicates corruption.
4262 */
4263 return SQLITE_CORRUPT_BKPT;
4264 }
4265
4266 nFree = get4byte(&pBt->pPage1->aData[36]);
4267 db = p->db;
4268 if( db->xAutovacPages ){
4269 int iDb;
4270 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
4271 if( db->aDb[iDb].pBt==p ) break;
4272 }
4273 nVac = db->xAutovacPages(
4274 db->pAutovacPagesArg,
4275 db->aDb[iDb].zDbSName,
4276 nOrig,
4277 nFree,
4278 pBt->pageSize
4279 );
4280 if( nVac>nFree ){
4281 nVac = nFree;
4282 }
4283 if( nVac==0 ){
4284 return SQLITE_OK;
4285 }
4286 }else{
4287 nVac = nFree;
4288 }
4289 nFin = finalDbSize(pBt, nOrig, nVac);
4290 if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
4291 if( nFin<nOrig ){
4292 rc = saveAllCursors(pBt, 0, 0);
4293 }
4294 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
4295 rc = incrVacuumStep(pBt, nFin, iFree, nVac==nFree);
4296 }
4297 if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
4298 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
4299 if( nVac==nFree ){
4300 put4byte(&pBt->pPage1->aData[32], 0);
4301 put4byte(&pBt->pPage1->aData[36], 0);
4302 }
4303 put4byte(&pBt->pPage1->aData[28], nFin);
4304 pBt->bDoTruncate = 1;
4305 pBt->nPage = nFin;
4306 }
4307 if( rc!=SQLITE_OK ){
4308 sqlite3PagerRollback(pPager);
4309 }
4310 }
4311
4312 assert( nRef>=sqlite3PagerRefcount(pPager) );
4313 return rc;
4314}
4315
4316#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
4317# define setChildPtrmaps(x) SQLITE_OK
4318#endif
4319
4320/*
4321** This routine does the first phase of a two-phase commit. This routine
4322** causes a rollback journal to be created (if it does not already exist)
4323** and populated with enough information so that if a power loss occurs
4324** the database can be restored to its original state by playing back
4325** the journal. Then the contents of the journal are flushed out to
4326** the disk. After the journal is safely on oxide, the changes to the
4327** database are written into the database file and flushed to oxide.
4328** At the end of this call, the rollback journal still exists on the
4329** disk and we are still holding all locks, so the transaction has not
4330** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
4331** commit process.
4332**
4333** This call is a no-op if no write-transaction is currently active on pBt.
4334**
4335** Otherwise, sync the database file for the btree pBt. zSuperJrnl points to
4336** the name of a super-journal file that should be written into the
4337** individual journal file, or is NULL, indicating no super-journal file
4338** (single database transaction).
4339**
4340** When this is called, the super-journal should already have been
4341** created, populated with this journal pointer and synced to disk.
4342**
4343** Once this is routine has returned, the only thing required to commit
4344** the write-transaction for this database file is to delete the journal.
4345*/
4346int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zSuperJrnl){
4347 int rc = SQLITE_OK;
4348 if( p->inTrans==TRANS_WRITE ){
4349 BtShared *pBt = p->pBt;
4350 sqlite3BtreeEnter(p);
4351#ifndef SQLITE_OMIT_AUTOVACUUM
4352 if( pBt->autoVacuum ){
4353 rc = autoVacuumCommit(p);
4354 if( rc!=SQLITE_OK ){
4355 sqlite3BtreeLeave(p);
4356 return rc;
4357 }
4358 }
4359 if( pBt->bDoTruncate ){
4360 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
4361 }
4362#endif
4363 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
4364 sqlite3BtreeLeave(p);
4365 }
4366 return rc;
4367}
4368
4369/*
4370** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
4371** at the conclusion of a transaction.
4372*/
4373static void btreeEndTransaction(Btree *p){
4374 BtShared *pBt = p->pBt;
4375 sqlite3 *db = p->db;
4376 assert( sqlite3BtreeHoldsMutex(p) );
4377
4378#ifndef SQLITE_OMIT_AUTOVACUUM
4379 pBt->bDoTruncate = 0;
4380#endif
4381 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
4382 /* If there are other active statements that belong to this database
4383 ** handle, downgrade to a read-only transaction. The other statements
4384 ** may still be reading from the database. */
4385 downgradeAllSharedCacheTableLocks(p);
4386 p->inTrans = TRANS_READ;
4387 }else{
4388 /* If the handle had any kind of transaction open, decrement the
4389 ** transaction count of the shared btree. If the transaction count
4390 ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
4391 ** call below will unlock the pager. */
4392 if( p->inTrans!=TRANS_NONE ){
4393 clearAllSharedCacheTableLocks(p);
4394 pBt->nTransaction--;
4395 if( 0==pBt->nTransaction ){
4396 pBt->inTransaction = TRANS_NONE;
4397 }
4398 }
4399
4400 /* Set the current transaction state to TRANS_NONE and unlock the
4401 ** pager if this call closed the only read or write transaction. */
4402 p->inTrans = TRANS_NONE;
4403 unlockBtreeIfUnused(pBt);
4404 }
4405
4406 btreeIntegrity(p);
4407}
4408
4409/*
4410** Commit the transaction currently in progress.
4411**
4412** This routine implements the second phase of a 2-phase commit. The
4413** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
4414** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
4415** routine did all the work of writing information out to disk and flushing the
4416** contents so that they are written onto the disk platter. All this
4417** routine has to do is delete or truncate or zero the header in the
4418** the rollback journal (which causes the transaction to commit) and
4419** drop locks.
4420**
4421** Normally, if an error occurs while the pager layer is attempting to
4422** finalize the underlying journal file, this function returns an error and
4423** the upper layer will attempt a rollback. However, if the second argument
4424** is non-zero then this b-tree transaction is part of a multi-file
4425** transaction. In this case, the transaction has already been committed
4426** (by deleting a super-journal file) and the caller will ignore this
4427** functions return code. So, even if an error occurs in the pager layer,
4428** reset the b-tree objects internal state to indicate that the write
4429** transaction has been closed. This is quite safe, as the pager will have
4430** transitioned to the error state.
4431**
4432** This will release the write lock on the database file. If there
4433** are no active cursors, it also releases the read lock.
4434*/
4435int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
4436
4437 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
4438 sqlite3BtreeEnter(p);
4439 btreeIntegrity(p);
4440
4441 /* If the handle has a write-transaction open, commit the shared-btrees
4442 ** transaction and set the shared state to TRANS_READ.
4443 */
4444 if( p->inTrans==TRANS_WRITE ){
4445 int rc;
4446 BtShared *pBt = p->pBt;
4447 assert( pBt->inTransaction==TRANS_WRITE );
4448 assert( pBt->nTransaction>0 );
4449 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
4450 if( rc!=SQLITE_OK && bCleanup==0 ){
4451 sqlite3BtreeLeave(p);
4452 return rc;
4453 }
4454 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
4455 pBt->inTransaction = TRANS_READ;
4456 btreeClearHasContent(pBt);
4457 }
4458
4459 btreeEndTransaction(p);
4460 sqlite3BtreeLeave(p);
4461 return SQLITE_OK;
4462}
4463
4464/*
4465** Do both phases of a commit.
4466*/
4467int sqlite3BtreeCommit(Btree *p){
4468 int rc;
4469 sqlite3BtreeEnter(p);
4470 rc = sqlite3BtreeCommitPhaseOne(p, 0);
4471 if( rc==SQLITE_OK ){
4472 rc = sqlite3BtreeCommitPhaseTwo(p, 0);
4473 }
4474 sqlite3BtreeLeave(p);
4475 return rc;
4476}
4477
4478/*
4479** This routine sets the state to CURSOR_FAULT and the error
4480** code to errCode for every cursor on any BtShared that pBtree
4481** references. Or if the writeOnly flag is set to 1, then only
4482** trip write cursors and leave read cursors unchanged.
4483**
4484** Every cursor is a candidate to be tripped, including cursors
4485** that belong to other database connections that happen to be
4486** sharing the cache with pBtree.
4487**
4488** This routine gets called when a rollback occurs. If the writeOnly
4489** flag is true, then only write-cursors need be tripped - read-only
4490** cursors save their current positions so that they may continue
4491** following the rollback. Or, if writeOnly is false, all cursors are
4492** tripped. In general, writeOnly is false if the transaction being
4493** rolled back modified the database schema. In this case b-tree root
4494** pages may be moved or deleted from the database altogether, making
4495** it unsafe for read cursors to continue.
4496**
4497** If the writeOnly flag is true and an error is encountered while
4498** saving the current position of a read-only cursor, all cursors,
4499** including all read-cursors are tripped.
4500**
4501** SQLITE_OK is returned if successful, or if an error occurs while
4502** saving a cursor position, an SQLite error code.
4503*/
4504int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
4505 BtCursor *p;
4506 int rc = SQLITE_OK;
4507
4508 assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
4509 if( pBtree ){
4510 sqlite3BtreeEnter(pBtree);
4511 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
4512 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
4513 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
4514 rc = saveCursorPosition(p);
4515 if( rc!=SQLITE_OK ){
4516 (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
4517 break;
4518 }
4519 }
4520 }else{
4521 sqlite3BtreeClearCursor(p);
4522 p->eState = CURSOR_FAULT;
4523 p->skipNext = errCode;
4524 }
4525 btreeReleaseAllCursorPages(p);
4526 }
4527 sqlite3BtreeLeave(pBtree);
4528 }
4529 return rc;
4530}
4531
4532/*
4533** Set the pBt->nPage field correctly, according to the current
4534** state of the database. Assume pBt->pPage1 is valid.
4535*/
4536static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
4537 int nPage = get4byte(&pPage1->aData[28]);
4538 testcase( nPage==0 );
4539 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
4540 testcase( pBt->nPage!=(u32)nPage );
4541 pBt->nPage = nPage;
4542}
4543
4544/*
4545** Rollback the transaction in progress.
4546**
4547** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
4548** Only write cursors are tripped if writeOnly is true but all cursors are
4549** tripped if writeOnly is false. Any attempt to use
4550** a tripped cursor will result in an error.
4551**
4552** This will release the write lock on the database file. If there
4553** are no active cursors, it also releases the read lock.
4554*/
4555int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
4556 int rc;
4557 BtShared *pBt = p->pBt;
4558 MemPage *pPage1;
4559
4560 assert( writeOnly==1 || writeOnly==0 );
4561 assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
4562 sqlite3BtreeEnter(p);
4563 if( tripCode==SQLITE_OK ){
4564 rc = tripCode = saveAllCursors(pBt, 0, 0);
4565 if( rc ) writeOnly = 0;
4566 }else{
4567 rc = SQLITE_OK;
4568 }
4569 if( tripCode ){
4570 int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
4571 assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
4572 if( rc2!=SQLITE_OK ) rc = rc2;
4573 }
4574 btreeIntegrity(p);
4575
4576 if( p->inTrans==TRANS_WRITE ){
4577 int rc2;
4578
4579 assert( TRANS_WRITE==pBt->inTransaction );
4580 rc2 = sqlite3PagerRollback(pBt->pPager);
4581 if( rc2!=SQLITE_OK ){
4582 rc = rc2;
4583 }
4584
4585 /* The rollback may have destroyed the pPage1->aData value. So
4586 ** call btreeGetPage() on page 1 again to make
4587 ** sure pPage1->aData is set correctly. */
4588 if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
4589 btreeSetNPage(pBt, pPage1);
4590 releasePageOne(pPage1);
4591 }
4592 assert( countValidCursors(pBt, 1)==0 );
4593 pBt->inTransaction = TRANS_READ;
4594 btreeClearHasContent(pBt);
4595 }
4596
4597 btreeEndTransaction(p);
4598 sqlite3BtreeLeave(p);
4599 return rc;
4600}
4601
4602/*
4603** Start a statement subtransaction. The subtransaction can be rolled
4604** back independently of the main transaction. You must start a transaction
4605** before starting a subtransaction. The subtransaction is ended automatically
4606** if the main transaction commits or rolls back.
4607**
4608** Statement subtransactions are used around individual SQL statements
4609** that are contained within a BEGIN...COMMIT block. If a constraint
4610** error occurs within the statement, the effect of that one statement
4611** can be rolled back without having to rollback the entire transaction.
4612**
4613** A statement sub-transaction is implemented as an anonymous savepoint. The
4614** value passed as the second parameter is the total number of savepoints,
4615** including the new anonymous savepoint, open on the B-Tree. i.e. if there
4616** are no active savepoints and no other statement-transactions open,
4617** iStatement is 1. This anonymous savepoint can be released or rolled back
4618** using the sqlite3BtreeSavepoint() function.
4619*/
4620int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
4621 int rc;
4622 BtShared *pBt = p->pBt;
4623 sqlite3BtreeEnter(p);
4624 assert( p->inTrans==TRANS_WRITE );
4625 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
4626 assert( iStatement>0 );
4627 assert( iStatement>p->db->nSavepoint );
4628 assert( pBt->inTransaction==TRANS_WRITE );
4629 /* At the pager level, a statement transaction is a savepoint with
4630 ** an index greater than all savepoints created explicitly using
4631 ** SQL statements. It is illegal to open, release or rollback any
4632 ** such savepoints while the statement transaction savepoint is active.
4633 */
4634 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
4635 sqlite3BtreeLeave(p);
4636 return rc;
4637}
4638
4639/*
4640** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
4641** or SAVEPOINT_RELEASE. This function either releases or rolls back the
4642** savepoint identified by parameter iSavepoint, depending on the value
4643** of op.
4644**
4645** Normally, iSavepoint is greater than or equal to zero. However, if op is
4646** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
4647** contents of the entire transaction are rolled back. This is different
4648** from a normal transaction rollback, as no locks are released and the
4649** transaction remains open.
4650*/
4651int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
4652 int rc = SQLITE_OK;
4653 if( p && p->inTrans==TRANS_WRITE ){
4654 BtShared *pBt = p->pBt;
4655 assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
4656 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
4657 sqlite3BtreeEnter(p);
4658 if( op==SAVEPOINT_ROLLBACK ){
4659 rc = saveAllCursors(pBt, 0, 0);
4660 }
4661 if( rc==SQLITE_OK ){
4662 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
4663 }
4664 if( rc==SQLITE_OK ){
4665 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
4666 pBt->nPage = 0;
4667 }
4668 rc = newDatabase(pBt);
4669 btreeSetNPage(pBt, pBt->pPage1);
4670
4671 /* pBt->nPage might be zero if the database was corrupt when
4672 ** the transaction was started. Otherwise, it must be at least 1. */
4673 assert( CORRUPT_DB || pBt->nPage>0 );
4674 }
4675 sqlite3BtreeLeave(p);
4676 }
4677 return rc;
4678}
4679
4680/*
4681** Create a new cursor for the BTree whose root is on the page
4682** iTable. If a read-only cursor is requested, it is assumed that
4683** the caller already has at least a read-only transaction open
4684** on the database already. If a write-cursor is requested, then
4685** the caller is assumed to have an open write transaction.
4686**
4687** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
4688** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
4689** can be used for reading or for writing if other conditions for writing
4690** are also met. These are the conditions that must be met in order
4691** for writing to be allowed:
4692**
4693** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
4694**
4695** 2: Other database connections that share the same pager cache
4696** but which are not in the READ_UNCOMMITTED state may not have
4697** cursors open with wrFlag==0 on the same table. Otherwise
4698** the changes made by this write cursor would be visible to
4699** the read cursors in the other database connection.
4700**
4701** 3: The database must be writable (not on read-only media)
4702**
4703** 4: There must be an active transaction.
4704**
4705** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
4706** is set. If FORDELETE is set, that is a hint to the implementation that
4707** this cursor will only be used to seek to and delete entries of an index
4708** as part of a larger DELETE statement. The FORDELETE hint is not used by
4709** this implementation. But in a hypothetical alternative storage engine
4710** in which index entries are automatically deleted when corresponding table
4711** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
4712** operations on this cursor can be no-ops and all READ operations can
4713** return a null row (2-bytes: 0x01 0x00).
4714**
4715** No checking is done to make sure that page iTable really is the
4716** root page of a b-tree. If it is not, then the cursor acquired
4717** will not work correctly.
4718**
4719** It is assumed that the sqlite3BtreeCursorZero() has been called
4720** on pCur to initialize the memory space prior to invoking this routine.
4721*/
4722static int btreeCursor(
4723 Btree *p, /* The btree */
4724 Pgno iTable, /* Root page of table to open */
4725 int wrFlag, /* 1 to write. 0 read-only */
4726 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4727 BtCursor *pCur /* Space for new cursor */
4728){
4729 BtShared *pBt = p->pBt; /* Shared b-tree handle */
4730 BtCursor *pX; /* Looping over other all cursors */
4731
4732 assert( sqlite3BtreeHoldsMutex(p) );
4733 assert( wrFlag==0
4734 || wrFlag==BTREE_WRCSR
4735 || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
4736 );
4737
4738 /* The following assert statements verify that if this is a sharable
4739 ** b-tree database, the connection is holding the required table locks,
4740 ** and that no other connection has any open cursor that conflicts with
4741 ** this lock. The iTable<1 term disables the check for corrupt schemas. */
4742 assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
4743 || iTable<1 );
4744 assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
4745
4746 /* Assert that the caller has opened the required transaction. */
4747 assert( p->inTrans>TRANS_NONE );
4748 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
4749 assert( pBt->pPage1 && pBt->pPage1->aData );
4750 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
4751
4752 if( iTable<=1 ){
4753 if( iTable<1 ){
4754 return SQLITE_CORRUPT_BKPT;
4755 }else if( btreePagecount(pBt)==0 ){
4756 assert( wrFlag==0 );
4757 iTable = 0;
4758 }
4759 }
4760
4761 /* Now that no other errors can occur, finish filling in the BtCursor
4762 ** variables and link the cursor into the BtShared list. */
4763 pCur->pgnoRoot = iTable;
4764 pCur->iPage = -1;
4765 pCur->pKeyInfo = pKeyInfo;
4766 pCur->pBtree = p;
4767 pCur->pBt = pBt;
4768 pCur->curFlags = 0;
4769 /* If there are two or more cursors on the same btree, then all such
4770 ** cursors *must* have the BTCF_Multiple flag set. */
4771 for(pX=pBt->pCursor; pX; pX=pX->pNext){
4772 if( pX->pgnoRoot==iTable ){
4773 pX->curFlags |= BTCF_Multiple;
4774 pCur->curFlags = BTCF_Multiple;
4775 }
4776 }
4777 pCur->eState = CURSOR_INVALID;
4778 pCur->pNext = pBt->pCursor;
4779 pBt->pCursor = pCur;
4780 if( wrFlag ){
4781 pCur->curFlags |= BTCF_WriteFlag;
4782 pCur->curPagerFlags = 0;
4783 if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
4784 }else{
4785 pCur->curPagerFlags = PAGER_GET_READONLY;
4786 }
4787 return SQLITE_OK;
4788}
4789static int btreeCursorWithLock(
4790 Btree *p, /* The btree */
4791 Pgno iTable, /* Root page of table to open */
4792 int wrFlag, /* 1 to write. 0 read-only */
4793 struct KeyInfo *pKeyInfo, /* First arg to comparison function */
4794 BtCursor *pCur /* Space for new cursor */
4795){
4796 int rc;
4797 sqlite3BtreeEnter(p);
4798 rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4799 sqlite3BtreeLeave(p);
4800 return rc;
4801}
4802int sqlite3BtreeCursor(
4803 Btree *p, /* The btree */
4804 Pgno iTable, /* Root page of table to open */
4805 int wrFlag, /* 1 to write. 0 read-only */
4806 struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
4807 BtCursor *pCur /* Write new cursor here */
4808){
4809 if( p->sharable ){
4810 return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
4811 }else{
4812 return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
4813 }
4814}
4815
4816/*
4817** Return the size of a BtCursor object in bytes.
4818**
4819** This interfaces is needed so that users of cursors can preallocate
4820** sufficient storage to hold a cursor. The BtCursor object is opaque
4821** to users so they cannot do the sizeof() themselves - they must call
4822** this routine.
4823*/
4824int sqlite3BtreeCursorSize(void){
4825 return ROUND8(sizeof(BtCursor));
4826}
4827
4828#ifdef SQLITE_DEBUG
4829/*
4830** Return true if and only if the Btree object will be automatically
4831** closed with the BtCursor closes. This is used within assert() statements
4832** only.
4833*/
4834int sqlite3BtreeClosesWithCursor(
4835 Btree *pBtree, /* the btree object */
4836 BtCursor *pCur /* Corresponding cursor */
4837){
4838 BtShared *pBt = pBtree->pBt;
4839 if( (pBt->openFlags & BTREE_SINGLE)==0 ) return 0;
4840 if( pBt->pCursor!=pCur ) return 0;
4841 if( pCur->pNext!=0 ) return 0;
4842 if( pCur->pBtree!=pBtree ) return 0;
4843 return 1;
4844}
4845#endif
4846
4847/*
4848** Initialize memory that will be converted into a BtCursor object.
4849**
4850** The simple approach here would be to memset() the entire object
4851** to zero. But it turns out that the apPage[] and aiIdx[] arrays
4852** do not need to be zeroed and they are large, so we can save a lot
4853** of run-time by skipping the initialization of those elements.
4854*/
4855void sqlite3BtreeCursorZero(BtCursor *p){
4856 memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
4857}
4858
4859/*
4860** Close a cursor. The read lock on the database file is released
4861** when the last cursor is closed.
4862*/
4863int sqlite3BtreeCloseCursor(BtCursor *pCur){
4864 Btree *pBtree = pCur->pBtree;
4865 if( pBtree ){
4866 BtShared *pBt = pCur->pBt;
4867 sqlite3BtreeEnter(pBtree);
4868 assert( pBt->pCursor!=0 );
4869 if( pBt->pCursor==pCur ){
4870 pBt->pCursor = pCur->pNext;
4871 }else{
4872 BtCursor *pPrev = pBt->pCursor;
4873 do{
4874 if( pPrev->pNext==pCur ){
4875 pPrev->pNext = pCur->pNext;
4876 break;
4877 }
4878 pPrev = pPrev->pNext;
4879 }while( ALWAYS(pPrev) );
4880 }
4881 btreeReleaseAllCursorPages(pCur);
4882 unlockBtreeIfUnused(pBt);
4883 sqlite3_free(pCur->aOverflow);
4884 sqlite3_free(pCur->pKey);
4885 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
4886 /* Since the BtShared is not sharable, there is no need to
4887 ** worry about the missing sqlite3BtreeLeave() call here. */
4888 assert( pBtree->sharable==0 );
4889 sqlite3BtreeClose(pBtree);
4890 }else{
4891 sqlite3BtreeLeave(pBtree);
4892 }
4893 pCur->pBtree = 0;
4894 }
4895 return SQLITE_OK;
4896}
4897
4898/*
4899** Make sure the BtCursor* given in the argument has a valid
4900** BtCursor.info structure. If it is not already valid, call
4901** btreeParseCell() to fill it in.
4902**
4903** BtCursor.info is a cache of the information in the current cell.
4904** Using this cache reduces the number of calls to btreeParseCell().
4905*/
4906#ifndef NDEBUG
4907 static int cellInfoEqual(CellInfo *a, CellInfo *b){
4908 if( a->nKey!=b->nKey ) return 0;
4909 if( a->pPayload!=b->pPayload ) return 0;
4910 if( a->nPayload!=b->nPayload ) return 0;
4911 if( a->nLocal!=b->nLocal ) return 0;
4912 if( a->nSize!=b->nSize ) return 0;
4913 return 1;
4914 }
4915 static void assertCellInfo(BtCursor *pCur){
4916 CellInfo info;
4917 memset(&info, 0, sizeof(info));
4918 btreeParseCell(pCur->pPage, pCur->ix, &info);
4919 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
4920 }
4921#else
4922 #define assertCellInfo(x)
4923#endif
4924static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
4925 if( pCur->info.nSize==0 ){
4926 pCur->curFlags |= BTCF_ValidNKey;
4927 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
4928 }else{
4929 assertCellInfo(pCur);
4930 }
4931}
4932
4933#ifndef NDEBUG /* The next routine used only within assert() statements */
4934/*
4935** Return true if the given BtCursor is valid. A valid cursor is one
4936** that is currently pointing to a row in a (non-empty) table.
4937** This is a verification routine is used only within assert() statements.
4938*/
4939int sqlite3BtreeCursorIsValid(BtCursor *pCur){
4940 return pCur && pCur->eState==CURSOR_VALID;
4941}
4942#endif /* NDEBUG */
4943int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
4944 assert( pCur!=0 );
4945 return pCur->eState==CURSOR_VALID;
4946}
4947
4948/*
4949** Return the value of the integer key or "rowid" for a table btree.
4950** This routine is only valid for a cursor that is pointing into a
4951** ordinary table btree. If the cursor points to an index btree or
4952** is invalid, the result of this routine is undefined.
4953*/
4954i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
4955 assert( cursorHoldsMutex(pCur) );
4956 assert( pCur->eState==CURSOR_VALID );
4957 assert( pCur->curIntKey );
4958 getCellInfo(pCur);
4959 return pCur->info.nKey;
4960}
4961
4962/*
4963** Pin or unpin a cursor.
4964*/
4965void sqlite3BtreeCursorPin(BtCursor *pCur){
4966 assert( (pCur->curFlags & BTCF_Pinned)==0 );
4967 pCur->curFlags |= BTCF_Pinned;
4968}
4969void sqlite3BtreeCursorUnpin(BtCursor *pCur){
4970 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
4971 pCur->curFlags &= ~BTCF_Pinned;
4972}
4973
4974/*
4975** Return the offset into the database file for the start of the
4976** payload to which the cursor is pointing.
4977*/
4978i64 sqlite3BtreeOffset(BtCursor *pCur){
4979 assert( cursorHoldsMutex(pCur) );
4980 assert( pCur->eState==CURSOR_VALID );
4981 getCellInfo(pCur);
4982 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
4983 (i64)(pCur->info.pPayload - pCur->pPage->aData);
4984}
4985
4986/*
4987** Return the number of bytes of payload for the entry that pCur is
4988** currently pointing to. For table btrees, this will be the amount
4989** of data. For index btrees, this will be the size of the key.
4990**
4991** The caller must guarantee that the cursor is pointing to a non-NULL
4992** valid entry. In other words, the calling procedure must guarantee
4993** that the cursor has Cursor.eState==CURSOR_VALID.
4994*/
4995u32 sqlite3BtreePayloadSize(BtCursor *pCur){
4996 assert( cursorHoldsMutex(pCur) );
4997 assert( pCur->eState==CURSOR_VALID );
4998 getCellInfo(pCur);
4999 return pCur->info.nPayload;
5000}
5001
5002/*
5003** Return an upper bound on the size of any record for the table
5004** that the cursor is pointing into.
5005**
5006** This is an optimization. Everything will still work if this
5007** routine always returns 2147483647 (which is the largest record
5008** that SQLite can handle) or more. But returning a smaller value might
5009** prevent large memory allocations when trying to interpret a
5010** corrupt database.
5011**
5012** The current implementation merely returns the size of the underlying
5013** database file.
5014*/
5015sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
5016 assert( cursorHoldsMutex(pCur) );
5017 assert( pCur->eState==CURSOR_VALID );
5018 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
5019}
5020
5021/*
5022** Given the page number of an overflow page in the database (parameter
5023** ovfl), this function finds the page number of the next page in the
5024** linked list of overflow pages. If possible, it uses the auto-vacuum
5025** pointer-map data instead of reading the content of page ovfl to do so.
5026**
5027** If an error occurs an SQLite error code is returned. Otherwise:
5028**
5029** The page number of the next overflow page in the linked list is
5030** written to *pPgnoNext. If page ovfl is the last page in its linked
5031** list, *pPgnoNext is set to zero.
5032**
5033** If ppPage is not NULL, and a reference to the MemPage object corresponding
5034** to page number pOvfl was obtained, then *ppPage is set to point to that
5035** reference. It is the responsibility of the caller to call releasePage()
5036** on *ppPage to free the reference. In no reference was obtained (because
5037** the pointer-map was used to obtain the value for *pPgnoNext), then
5038** *ppPage is set to zero.
5039*/
5040static int getOverflowPage(
5041 BtShared *pBt, /* The database file */
5042 Pgno ovfl, /* Current overflow page number */
5043 MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
5044 Pgno *pPgnoNext /* OUT: Next overflow page number */
5045){
5046 Pgno next = 0;
5047 MemPage *pPage = 0;
5048 int rc = SQLITE_OK;
5049
5050 assert( sqlite3_mutex_held(pBt->mutex) );
5051 assert(pPgnoNext);
5052
5053#ifndef SQLITE_OMIT_AUTOVACUUM
5054 /* Try to find the next page in the overflow list using the
5055 ** autovacuum pointer-map pages. Guess that the next page in
5056 ** the overflow list is page number (ovfl+1). If that guess turns
5057 ** out to be wrong, fall back to loading the data of page
5058 ** number ovfl to determine the next page number.
5059 */
5060 if( pBt->autoVacuum ){
5061 Pgno pgno;
5062 Pgno iGuess = ovfl+1;
5063 u8 eType;
5064
5065 while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
5066 iGuess++;
5067 }
5068
5069 if( iGuess<=btreePagecount(pBt) ){
5070 rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
5071 if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
5072 next = iGuess;
5073 rc = SQLITE_DONE;
5074 }
5075 }
5076 }
5077#endif
5078
5079 assert( next==0 || rc==SQLITE_DONE );
5080 if( rc==SQLITE_OK ){
5081 rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
5082 assert( rc==SQLITE_OK || pPage==0 );
5083 if( rc==SQLITE_OK ){
5084 next = get4byte(pPage->aData);
5085 }
5086 }
5087
5088 *pPgnoNext = next;
5089 if( ppPage ){
5090 *ppPage = pPage;
5091 }else{
5092 releasePage(pPage);
5093 }
5094 return (rc==SQLITE_DONE ? SQLITE_OK : rc);
5095}
5096
5097/*
5098** Copy data from a buffer to a page, or from a page to a buffer.
5099**
5100** pPayload is a pointer to data stored on database page pDbPage.
5101** If argument eOp is false, then nByte bytes of data are copied
5102** from pPayload to the buffer pointed at by pBuf. If eOp is true,
5103** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
5104** of data are copied from the buffer pBuf to pPayload.
5105**
5106** SQLITE_OK is returned on success, otherwise an error code.
5107*/
5108static int copyPayload(
5109 void *pPayload, /* Pointer to page data */
5110 void *pBuf, /* Pointer to buffer */
5111 int nByte, /* Number of bytes to copy */
5112 int eOp, /* 0 -> copy from page, 1 -> copy to page */
5113 DbPage *pDbPage /* Page containing pPayload */
5114){
5115 if( eOp ){
5116 /* Copy data from buffer to page (a write operation) */
5117 int rc = sqlite3PagerWrite(pDbPage);
5118 if( rc!=SQLITE_OK ){
5119 return rc;
5120 }
5121 memcpy(pPayload, pBuf, nByte);
5122 }else{
5123 /* Copy data from page to buffer (a read operation) */
5124 memcpy(pBuf, pPayload, nByte);
5125 }
5126 return SQLITE_OK;
5127}
5128
5129/*
5130** This function is used to read or overwrite payload information
5131** for the entry that the pCur cursor is pointing to. The eOp
5132** argument is interpreted as follows:
5133**
5134** 0: The operation is a read. Populate the overflow cache.
5135** 1: The operation is a write. Populate the overflow cache.
5136**
5137** A total of "amt" bytes are read or written beginning at "offset".
5138** Data is read to or from the buffer pBuf.
5139**
5140** The content being read or written might appear on the main page
5141** or be scattered out on multiple overflow pages.
5142**
5143** If the current cursor entry uses one or more overflow pages
5144** this function may allocate space for and lazily populate
5145** the overflow page-list cache array (BtCursor.aOverflow).
5146** Subsequent calls use this cache to make seeking to the supplied offset
5147** more efficient.
5148**
5149** Once an overflow page-list cache has been allocated, it must be
5150** invalidated if some other cursor writes to the same table, or if
5151** the cursor is moved to a different row. Additionally, in auto-vacuum
5152** mode, the following events may invalidate an overflow page-list cache.
5153**
5154** * An incremental vacuum,
5155** * A commit in auto_vacuum="full" mode,
5156** * Creating a table (may require moving an overflow page).
5157*/
5158static int accessPayload(
5159 BtCursor *pCur, /* Cursor pointing to entry to read from */
5160 u32 offset, /* Begin reading this far into payload */
5161 u32 amt, /* Read this many bytes */
5162 unsigned char *pBuf, /* Write the bytes into this buffer */
5163 int eOp /* zero to read. non-zero to write. */
5164){
5165 unsigned char *aPayload;
5166 int rc = SQLITE_OK;
5167 int iIdx = 0;
5168 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
5169 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
5170#ifdef SQLITE_DIRECT_OVERFLOW_READ
5171 unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
5172#endif
5173
5174 assert( pPage );
5175 assert( eOp==0 || eOp==1 );
5176 assert( pCur->eState==CURSOR_VALID );
5177 if( pCur->ix>=pPage->nCell ){
5178 return SQLITE_CORRUPT_PAGE(pPage);
5179 }
5180 assert( cursorHoldsMutex(pCur) );
5181
5182 getCellInfo(pCur);
5183 aPayload = pCur->info.pPayload;
5184 assert( (u64)offset+(u64)amt <= (u64)pCur->info.nPayload );
5185
5186 assert( aPayload > pPage->aData );
5187 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
5188 /* Trying to read or write past the end of the data is an error. The
5189 ** conditional above is really:
5190 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
5191 ** but is recast into its current form to avoid integer overflow problems
5192 */
5193 return SQLITE_CORRUPT_PAGE(pPage);
5194 }
5195
5196 /* Check if data must be read/written to/from the btree page itself. */
5197 if( offset<pCur->info.nLocal ){
5198 int a = amt;
5199 if( a+offset>pCur->info.nLocal ){
5200 a = pCur->info.nLocal - offset;
5201 }
5202 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
5203 offset = 0;
5204 pBuf += a;
5205 amt -= a;
5206 }else{
5207 offset -= pCur->info.nLocal;
5208 }
5209
5210
5211 if( rc==SQLITE_OK && amt>0 ){
5212 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
5213 Pgno nextPage;
5214
5215 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
5216
5217 /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
5218 **
5219 ** The aOverflow[] array is sized at one entry for each overflow page
5220 ** in the overflow chain. The page number of the first overflow page is
5221 ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
5222 ** means "not yet known" (the cache is lazily populated).
5223 */
5224 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
5225 i64 nOvfl = pCur->info.nPayload;
5226 testcase( nOvfl - pCur->info.nLocal + ovflSize - 1 > 0xffffffffU );
5227 nOvfl = (nOvfl - pCur->info.nLocal + ovflSize-1)/ovflSize;
5228 if( pCur->aOverflow==0
5229 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
5230 ){
5231 Pgno *aNew;
5232 if( sqlite3FaultSim(413) ){
5233 aNew = 0;
5234 }else{
5235 aNew = (Pgno*)sqlite3Realloc(pCur->aOverflow, nOvfl*2*sizeof(Pgno));
5236 }
5237 if( aNew==0 ){
5238 return SQLITE_NOMEM_BKPT;
5239 }else{
5240 pCur->aOverflow = aNew;
5241 }
5242 }
5243 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
5244 pCur->curFlags |= BTCF_ValidOvfl;
5245 }else{
5246 /* Sanity check the validity of the overflow page cache */
5247 assert( pCur->aOverflow[0]==nextPage
5248 || pCur->aOverflow[0]==0
5249 || CORRUPT_DB );
5250 assert( pCur->aOverflow[0]!=0 || pCur->aOverflow[offset/ovflSize]==0 );
5251
5252 /* If the overflow page-list cache has been allocated and the
5253 ** entry for the first required overflow page is valid, skip
5254 ** directly to it.
5255 */
5256 if( pCur->aOverflow[offset/ovflSize] ){
5257 iIdx = (offset/ovflSize);
5258 nextPage = pCur->aOverflow[iIdx];
5259 offset = (offset%ovflSize);
5260 }
5261 }
5262
5263 assert( rc==SQLITE_OK && amt>0 );
5264 while( nextPage ){
5265 /* If required, populate the overflow page-list cache. */
5266 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
5267 assert( pCur->aOverflow[iIdx]==0
5268 || pCur->aOverflow[iIdx]==nextPage
5269 || CORRUPT_DB );
5270 pCur->aOverflow[iIdx] = nextPage;
5271
5272 if( offset>=ovflSize ){
5273 /* The only reason to read this page is to obtain the page
5274 ** number for the next page in the overflow chain. The page
5275 ** data is not required. So first try to lookup the overflow
5276 ** page-list cache, if any, then fall back to the getOverflowPage()
5277 ** function.
5278 */
5279 assert( pCur->curFlags & BTCF_ValidOvfl );
5280 assert( pCur->pBtree->db==pBt->db );
5281 if( pCur->aOverflow[iIdx+1] ){
5282 nextPage = pCur->aOverflow[iIdx+1];
5283 }else{
5284 rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
5285 }
5286 offset -= ovflSize;
5287 }else{
5288 /* Need to read this page properly. It contains some of the
5289 ** range of data that is being read (eOp==0) or written (eOp!=0).
5290 */
5291 int a = amt;
5292 if( a + offset > ovflSize ){
5293 a = ovflSize - offset;
5294 }
5295
5296#ifdef SQLITE_DIRECT_OVERFLOW_READ
5297 /* If all the following are true:
5298 **
5299 ** 1) this is a read operation, and
5300 ** 2) data is required from the start of this overflow page, and
5301 ** 3) there are no dirty pages in the page-cache
5302 ** 4) the database is file-backed, and
5303 ** 5) the page is not in the WAL file
5304 ** 6) at least 4 bytes have already been read into the output buffer
5305 **
5306 ** then data can be read directly from the database file into the
5307 ** output buffer, bypassing the page-cache altogether. This speeds
5308 ** up loading large records that span many overflow pages.
5309 */
5310 if( eOp==0 /* (1) */
5311 && offset==0 /* (2) */
5312 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
5313 && &pBuf[-4]>=pBufStart /* (6) */
5314 ){
5315 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
5316 u8 aSave[4];
5317 u8 *aWrite = &pBuf[-4];
5318 assert( aWrite>=pBufStart ); /* due to (6) */
5319 memcpy(aSave, aWrite, 4);
5320 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
5321 nextPage = get4byte(aWrite);
5322 memcpy(aWrite, aSave, 4);
5323 }else
5324#endif
5325
5326 {
5327 DbPage *pDbPage;
5328 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
5329 (eOp==0 ? PAGER_GET_READONLY : 0)
5330 );
5331 if( rc==SQLITE_OK ){
5332 if( eOp!=0
5333 && (sqlite3PagerPageRefcount(pDbPage)!=1
5334 || NEVER(((MemPage*)sqlite3PagerGetExtra(pDbPage))->isInit))
5335 && sqlite3FaultSim(411)==SQLITE_OK
5336 ){
5337 sqlite3PagerUnref(pDbPage);
5338 return SQLITE_CORRUPT_PAGE(pPage);
5339 }
5340 aPayload = sqlite3PagerGetData(pDbPage);
5341 nextPage = get4byte(aPayload);
5342 rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
5343 sqlite3PagerUnref(pDbPage);
5344 offset = 0;
5345 }
5346 }
5347 amt -= a;
5348 if( amt==0 ) return rc;
5349 pBuf += a;
5350 }
5351 if( rc ) break;
5352 iIdx++;
5353 }
5354 }
5355
5356 if( rc==SQLITE_OK && amt>0 ){
5357 /* Overflow chain ends prematurely */
5358 return SQLITE_CORRUPT_PAGE(pPage);
5359 }
5360 return rc;
5361}
5362
5363/*
5364** Read part of the payload for the row at which that cursor pCur is currently
5365** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
5366** begins at "offset".
5367**
5368** pCur can be pointing to either a table or an index b-tree.
5369** If pointing to a table btree, then the content section is read. If
5370** pCur is pointing to an index b-tree then the key section is read.
5371**
5372** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
5373** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
5374** cursor might be invalid or might need to be restored before being read.
5375**
5376** Return SQLITE_OK on success or an error code if anything goes
5377** wrong. An error is returned if "offset+amt" is larger than
5378** the available payload.
5379*/
5380int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5381 assert( cursorHoldsMutex(pCur) );
5382 assert( pCur->eState==CURSOR_VALID );
5383 assert( pCur->iPage>=0 && pCur->pPage );
5384 return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
5385}
5386
5387/*
5388** This variant of sqlite3BtreePayload() works even if the cursor has not
5389** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
5390** interface.
5391*/
5392#ifndef SQLITE_OMIT_INCRBLOB
5393static SQLITE_NOINLINE int accessPayloadChecked(
5394 BtCursor *pCur,
5395 u32 offset,
5396 u32 amt,
5397 void *pBuf
5398){
5399 int rc;
5400 if ( pCur->eState==CURSOR_INVALID ){
5401 return SQLITE_ABORT;
5402 }
5403 assert( cursorOwnsBtShared(pCur) );
5404 rc = btreeRestoreCursorPosition(pCur);
5405 return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
5406}
5407int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
5408 if( pCur->eState==CURSOR_VALID ){
5409 assert( cursorOwnsBtShared(pCur) );
5410 return accessPayload(pCur, offset, amt, pBuf, 0);
5411 }else{
5412 return accessPayloadChecked(pCur, offset, amt, pBuf);
5413 }
5414}
5415#endif /* SQLITE_OMIT_INCRBLOB */
5416
5417/*
5418** Return a pointer to payload information from the entry that the
5419** pCur cursor is pointing to. The pointer is to the beginning of
5420** the key if index btrees (pPage->intKey==0) and is the data for
5421** table btrees (pPage->intKey==1). The number of bytes of available
5422** key/data is written into *pAmt. If *pAmt==0, then the value
5423** returned will not be a valid pointer.
5424**
5425** This routine is an optimization. It is common for the entire key
5426** and data to fit on the local page and for there to be no overflow
5427** pages. When that is so, this routine can be used to access the
5428** key and data without making a copy. If the key and/or data spills
5429** onto overflow pages, then accessPayload() must be used to reassemble
5430** the key/data and copy it into a preallocated buffer.
5431**
5432** The pointer returned by this routine looks directly into the cached
5433** page of the database. The data might change or move the next time
5434** any btree routine is called.
5435*/
5436static const void *fetchPayload(
5437 BtCursor *pCur, /* Cursor pointing to entry to read from */
5438 u32 *pAmt /* Write the number of available bytes here */
5439){
5440 int amt;
5441 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
5442 assert( pCur->eState==CURSOR_VALID );
5443 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5444 assert( cursorOwnsBtShared(pCur) );
5445 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
5446 assert( pCur->info.nSize>0 );
5447 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
5448 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
5449 amt = pCur->info.nLocal;
5450 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
5451 /* There is too little space on the page for the expected amount
5452 ** of local content. Database must be corrupt. */
5453 assert( CORRUPT_DB );
5454 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
5455 }
5456 *pAmt = (u32)amt;
5457 return (void*)pCur->info.pPayload;
5458}
5459
5460
5461/*
5462** For the entry that cursor pCur is point to, return as
5463** many bytes of the key or data as are available on the local
5464** b-tree page. Write the number of available bytes into *pAmt.
5465**
5466** The pointer returned is ephemeral. The key/data may move
5467** or be destroyed on the next call to any Btree routine,
5468** including calls from other threads against the same cache.
5469** Hence, a mutex on the BtShared should be held prior to calling
5470** this routine.
5471**
5472** These routines is used to get quick access to key and data
5473** in the common case where no overflow pages are used.
5474*/
5475const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
5476 return fetchPayload(pCur, pAmt);
5477}
5478
5479
5480/*
5481** Move the cursor down to a new child page. The newPgno argument is the
5482** page number of the child page to move to.
5483**
5484** This function returns SQLITE_CORRUPT if the page-header flags field of
5485** the new child page does not match the flags field of the parent (i.e.
5486** if an intkey page appears to be the parent of a non-intkey page, or
5487** vice-versa).
5488*/
5489static int moveToChild(BtCursor *pCur, u32 newPgno){
5490 int rc;
5491 assert( cursorOwnsBtShared(pCur) );
5492 assert( pCur->eState==CURSOR_VALID );
5493 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
5494 assert( pCur->iPage>=0 );
5495 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
5496 return SQLITE_CORRUPT_BKPT;
5497 }
5498 pCur->info.nSize = 0;
5499 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5500 pCur->aiIdx[pCur->iPage] = pCur->ix;
5501 pCur->apPage[pCur->iPage] = pCur->pPage;
5502 pCur->ix = 0;
5503 pCur->iPage++;
5504 rc = getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur->curPagerFlags);
5505 assert( pCur->pPage!=0 || rc!=SQLITE_OK );
5506 if( rc==SQLITE_OK
5507 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
5508 ){
5509 releasePage(pCur->pPage);
5510 rc = SQLITE_CORRUPT_PGNO(newPgno);
5511 }
5512 if( rc ){
5513 pCur->pPage = pCur->apPage[--pCur->iPage];
5514 }
5515 return rc;
5516}
5517
5518#ifdef SQLITE_DEBUG
5519/*
5520** Page pParent is an internal (non-leaf) tree page. This function
5521** asserts that page number iChild is the left-child if the iIdx'th
5522** cell in page pParent. Or, if iIdx is equal to the total number of
5523** cells in pParent, that page number iChild is the right-child of
5524** the page.
5525*/
5526static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
5527 if( CORRUPT_DB ) return; /* The conditions tested below might not be true
5528 ** in a corrupt database */
5529 assert( iIdx<=pParent->nCell );
5530 if( iIdx==pParent->nCell ){
5531 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
5532 }else{
5533 assert( get4byte(findCell(pParent, iIdx))==iChild );
5534 }
5535}
5536#else
5537# define assertParentIndex(x,y,z)
5538#endif
5539
5540/*
5541** Move the cursor up to the parent page.
5542**
5543** pCur->idx is set to the cell index that contains the pointer
5544** to the page we are coming from. If we are coming from the
5545** right-most child page then pCur->idx is set to one more than
5546** the largest cell index.
5547*/
5548static void moveToParent(BtCursor *pCur){
5549 MemPage *pLeaf;
5550 assert( cursorOwnsBtShared(pCur) );
5551 assert( pCur->eState==CURSOR_VALID );
5552 assert( pCur->iPage>0 );
5553 assert( pCur->pPage );
5554 assertParentIndex(
5555 pCur->apPage[pCur->iPage-1],
5556 pCur->aiIdx[pCur->iPage-1],
5557 pCur->pPage->pgno
5558 );
5559 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
5560 pCur->info.nSize = 0;
5561 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
5562 pCur->ix = pCur->aiIdx[pCur->iPage-1];
5563 pLeaf = pCur->pPage;
5564 pCur->pPage = pCur->apPage[--pCur->iPage];
5565 releasePageNotNull(pLeaf);
5566}
5567
5568/*
5569** Move the cursor to point to the root page of its b-tree structure.
5570**
5571** If the table has a virtual root page, then the cursor is moved to point
5572** to the virtual root page instead of the actual root page. A table has a
5573** virtual root page when the actual root page contains no cells and a
5574** single child page. This can only happen with the table rooted at page 1.
5575**
5576** If the b-tree structure is empty, the cursor state is set to
5577** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
5578** the cursor is set to point to the first cell located on the root
5579** (or virtual root) page and the cursor state is set to CURSOR_VALID.
5580**
5581** If this function returns successfully, it may be assumed that the
5582** page-header flags indicate that the [virtual] root-page is the expected
5583** kind of b-tree page (i.e. if when opening the cursor the caller did not
5584** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
5585** indicating a table b-tree, or if the caller did specify a KeyInfo
5586** structure the flags byte is set to 0x02 or 0x0A, indicating an index
5587** b-tree).
5588*/
5589static int moveToRoot(BtCursor *pCur){
5590 MemPage *pRoot;
5591 int rc = SQLITE_OK;
5592
5593 assert( cursorOwnsBtShared(pCur) );
5594 assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
5595 assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
5596 assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
5597 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
5598 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
5599
5600 if( pCur->iPage>=0 ){
5601 if( pCur->iPage ){
5602 releasePageNotNull(pCur->pPage);
5603 while( --pCur->iPage ){
5604 releasePageNotNull(pCur->apPage[pCur->iPage]);
5605 }
5606 pRoot = pCur->pPage = pCur->apPage[0];
5607 goto skip_init;
5608 }
5609 }else if( pCur->pgnoRoot==0 ){
5610 pCur->eState = CURSOR_INVALID;
5611 return SQLITE_EMPTY;
5612 }else{
5613 assert( pCur->iPage==(-1) );
5614 if( pCur->eState>=CURSOR_REQUIRESEEK ){
5615 if( pCur->eState==CURSOR_FAULT ){
5616 assert( pCur->skipNext!=SQLITE_OK );
5617 return pCur->skipNext;
5618 }
5619 sqlite3BtreeClearCursor(pCur);
5620 }
5621 rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
5622 pCur->curPagerFlags);
5623 if( rc!=SQLITE_OK ){
5624 pCur->eState = CURSOR_INVALID;
5625 return rc;
5626 }
5627 pCur->iPage = 0;
5628 pCur->curIntKey = pCur->pPage->intKey;
5629 }
5630 pRoot = pCur->pPage;
5631 assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
5632
5633 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
5634 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
5635 ** NULL, the caller expects a table b-tree. If this is not the case,
5636 ** return an SQLITE_CORRUPT error.
5637 **
5638 ** Earlier versions of SQLite assumed that this test could not fail
5639 ** if the root page was already loaded when this function was called (i.e.
5640 ** if pCur->iPage>=0). But this is not so if the database is corrupted
5641 ** in such a way that page pRoot is linked into a second b-tree table
5642 ** (or the freelist). */
5643 assert( pRoot->intKey==1 || pRoot->intKey==0 );
5644 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
5645 return SQLITE_CORRUPT_PAGE(pCur->pPage);
5646 }
5647
5648skip_init:
5649 pCur->ix = 0;
5650 pCur->info.nSize = 0;
5651 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
5652
5653 if( pRoot->nCell>0 ){
5654 pCur->eState = CURSOR_VALID;
5655 }else if( !pRoot->leaf ){
5656 Pgno subpage;
5657 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
5658 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
5659 pCur->eState = CURSOR_VALID;
5660 rc = moveToChild(pCur, subpage);
5661 }else{
5662 pCur->eState = CURSOR_INVALID;
5663 rc = SQLITE_EMPTY;
5664 }
5665 return rc;
5666}
5667
5668/*
5669** Move the cursor down to the left-most leaf entry beneath the
5670** entry to which it is currently pointing.
5671**
5672** The left-most leaf is the one with the smallest key - the first
5673** in ascending order.
5674*/
5675static int moveToLeftmost(BtCursor *pCur){
5676 Pgno pgno;
5677 int rc = SQLITE_OK;
5678 MemPage *pPage;
5679
5680 assert( cursorOwnsBtShared(pCur) );
5681 assert( pCur->eState==CURSOR_VALID );
5682 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
5683 assert( pCur->ix<pPage->nCell );
5684 pgno = get4byte(findCell(pPage, pCur->ix));
5685 rc = moveToChild(pCur, pgno);
5686 }
5687 return rc;
5688}
5689
5690/*
5691** Move the cursor down to the right-most leaf entry beneath the
5692** page to which it is currently pointing. Notice the difference
5693** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
5694** finds the left-most entry beneath the *entry* whereas moveToRightmost()
5695** finds the right-most entry beneath the *page*.
5696**
5697** The right-most entry is the one with the largest key - the last
5698** key in ascending order.
5699*/
5700static int moveToRightmost(BtCursor *pCur){
5701 Pgno pgno;
5702 int rc = SQLITE_OK;
5703 MemPage *pPage = 0;
5704
5705 assert( cursorOwnsBtShared(pCur) );
5706 assert( pCur->eState==CURSOR_VALID );
5707 while( !(pPage = pCur->pPage)->leaf ){
5708 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5709 pCur->ix = pPage->nCell;
5710 rc = moveToChild(pCur, pgno);
5711 if( rc ) return rc;
5712 }
5713 pCur->ix = pPage->nCell-1;
5714 assert( pCur->info.nSize==0 );
5715 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
5716 return SQLITE_OK;
5717}
5718
5719/* Move the cursor to the first entry in the table. Return SQLITE_OK
5720** on success. Set *pRes to 0 if the cursor actually points to something
5721** or set *pRes to 1 if the table is empty.
5722*/
5723int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
5724 int rc;
5725
5726 assert( cursorOwnsBtShared(pCur) );
5727 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5728 rc = moveToRoot(pCur);
5729 if( rc==SQLITE_OK ){
5730 assert( pCur->pPage->nCell>0 );
5731 *pRes = 0;
5732 rc = moveToLeftmost(pCur);
5733 }else if( rc==SQLITE_EMPTY ){
5734 assert( pCur->pgnoRoot==0 || (pCur->pPage!=0 && pCur->pPage->nCell==0) );
5735 *pRes = 1;
5736 rc = SQLITE_OK;
5737 }
5738 return rc;
5739}
5740
5741/* Set *pRes to 1 (true) if the BTree pointed to by cursor pCur contains zero
5742** rows of content. Set *pRes to 0 (false) if the table contains content.
5743** Return SQLITE_OK on success or some error code (ex: SQLITE_NOMEM) if
5744** something goes wrong.
5745*/
5746int sqlite3BtreeIsEmpty(BtCursor *pCur, int *pRes){
5747 int rc;
5748
5749 assert( cursorOwnsBtShared(pCur) );
5750 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5751 if( NEVER(pCur->eState==CURSOR_VALID) ){
5752 *pRes = 0;
5753 return SQLITE_OK;
5754 }
5755 rc = moveToRoot(pCur);
5756 if( rc==SQLITE_EMPTY ){
5757 *pRes = 1;
5758 rc = SQLITE_OK;
5759 }else{
5760 *pRes = 0;
5761 }
5762 return rc;
5763}
5764
5765#ifdef SQLITE_DEBUG
5766/* The cursors is CURSOR_VALID and has BTCF_AtLast set. Verify that
5767** this flags are true for a consistent database.
5768**
5769** This routine is is called from within assert() statements only.
5770** It is an internal verification routine and does not appear in production
5771** builds.
5772*/
5773static int cursorIsAtLastEntry(BtCursor *pCur){
5774 int ii;
5775 for(ii=0; ii<pCur->iPage; ii++){
5776 if( pCur->aiIdx[ii]!=pCur->apPage[ii]->nCell ) return 0;
5777 }
5778 return pCur->ix==pCur->pPage->nCell-1 && pCur->pPage->leaf!=0;
5779}
5780#endif
5781
5782/* Move the cursor to the last entry in the table. Return SQLITE_OK
5783** on success. Set *pRes to 0 if the cursor actually points to something
5784** or set *pRes to 1 if the table is empty.
5785*/
5786static SQLITE_NOINLINE int btreeLast(BtCursor *pCur, int *pRes){
5787 int rc = moveToRoot(pCur);
5788 if( rc==SQLITE_OK ){
5789 assert( pCur->eState==CURSOR_VALID );
5790 *pRes = 0;
5791 rc = moveToRightmost(pCur);
5792 if( rc==SQLITE_OK ){
5793 pCur->curFlags |= BTCF_AtLast;
5794 }else{
5795 pCur->curFlags &= ~BTCF_AtLast;
5796 }
5797 }else if( rc==SQLITE_EMPTY ){
5798 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5799 *pRes = 1;
5800 rc = SQLITE_OK;
5801 }
5802 return rc;
5803}
5804int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
5805 assert( cursorOwnsBtShared(pCur) );
5806 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5807
5808 /* If the cursor already points to the last entry, this is a no-op. */
5809 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
5810 assert( cursorIsAtLastEntry(pCur) || CORRUPT_DB );
5811 *pRes = 0;
5812 return SQLITE_OK;
5813 }
5814 return btreeLast(pCur, pRes);
5815}
5816
5817/* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
5818** table near the key intKey. Return a success code.
5819**
5820** If an exact match is not found, then the cursor is always
5821** left pointing at a leaf page which would hold the entry if it
5822** were present. The cursor might point to an entry that comes
5823** before or after the key.
5824**
5825** An integer is written into *pRes which is the result of
5826** comparing the key with the entry to which the cursor is
5827** pointing. The meaning of the integer written into
5828** *pRes is as follows:
5829**
5830** *pRes<0 The cursor is left pointing at an entry that
5831** is smaller than intKey or if the table is empty
5832** and the cursor is therefore left point to nothing.
5833**
5834** *pRes==0 The cursor is left pointing at an entry that
5835** exactly matches intKey.
5836**
5837** *pRes>0 The cursor is left pointing at an entry that
5838** is larger than intKey.
5839*/
5840int sqlite3BtreeTableMoveto(
5841 BtCursor *pCur, /* The cursor to be moved */
5842 i64 intKey, /* The table key */
5843 int biasRight, /* If true, bias the search to the high end */
5844 int *pRes /* Write search results here */
5845){
5846 int rc;
5847
5848 assert( cursorOwnsBtShared(pCur) );
5849 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
5850 assert( pRes );
5851 assert( pCur->pKeyInfo==0 );
5852 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
5853
5854 /* If the cursor is already positioned at the point we are trying
5855 ** to move to, then just return without doing any work */
5856 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
5857 if( pCur->info.nKey==intKey ){
5858 *pRes = 0;
5859 return SQLITE_OK;
5860 }
5861 if( pCur->info.nKey<intKey ){
5862 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
5863 assert( cursorIsAtLastEntry(pCur) || CORRUPT_DB );
5864 *pRes = -1;
5865 return SQLITE_OK;
5866 }
5867 /* If the requested key is one more than the previous key, then
5868 ** try to get there using sqlite3BtreeNext() rather than a full
5869 ** binary search. This is an optimization only. The correct answer
5870 ** is still obtained without this case, only a little more slowly. */
5871 if( pCur->info.nKey+1==intKey ){
5872 *pRes = 0;
5873 rc = sqlite3BtreeNext(pCur, 0);
5874 if( rc==SQLITE_OK ){
5875 getCellInfo(pCur);
5876 if( pCur->info.nKey==intKey ){
5877 return SQLITE_OK;
5878 }
5879 }else if( rc!=SQLITE_DONE ){
5880 return rc;
5881 }
5882 }
5883 }
5884 }
5885
5886#ifdef SQLITE_DEBUG
5887 pCur->pBtree->nSeek++; /* Performance measurement during testing */
5888#endif
5889
5890 rc = moveToRoot(pCur);
5891 if( rc ){
5892 if( rc==SQLITE_EMPTY ){
5893 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
5894 *pRes = -1;
5895 return SQLITE_OK;
5896 }
5897 return rc;
5898 }
5899 assert( pCur->pPage );
5900 assert( pCur->pPage->isInit );
5901 assert( pCur->eState==CURSOR_VALID );
5902 assert( pCur->pPage->nCell > 0 );
5903 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
5904 assert( pCur->curIntKey );
5905
5906 for(;;){
5907 int lwr, upr, idx, c;
5908 Pgno chldPg;
5909 MemPage *pPage = pCur->pPage;
5910 u8 *pCell; /* Pointer to current cell in pPage */
5911
5912 /* pPage->nCell must be greater than zero. If this is the root-page
5913 ** the cursor would have been INVALID above and this for(;;) loop
5914 ** not run. If this is not the root-page, then the moveToChild() routine
5915 ** would have already detected db corruption. Similarly, pPage must
5916 ** be the right kind (index or table) of b-tree page. Otherwise
5917 ** a moveToChild() or moveToRoot() call would have detected corruption. */
5918 assert( pPage->nCell>0 );
5919 assert( pPage->intKey );
5920 lwr = 0;
5921 upr = pPage->nCell-1;
5922 assert( biasRight==0 || biasRight==1 );
5923 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
5924 for(;;){
5925 i64 nCellKey;
5926 pCell = findCellPastPtr(pPage, idx);
5927 if( pPage->intKeyLeaf ){
5928 while( 0x80 <= *(pCell++) ){
5929 if( pCell>=pPage->aDataEnd ){
5930 return SQLITE_CORRUPT_PAGE(pPage);
5931 }
5932 }
5933 }
5934 nCellKey = sqlite3VarintValue(pCell);
5935 if( nCellKey<intKey ){
5936 lwr = idx+1;
5937 if( lwr>upr ){ c = -1; break; }
5938 }else if( nCellKey>intKey ){
5939 upr = idx-1;
5940 if( lwr>upr ){ c = +1; break; }
5941 }else{
5942 assert( nCellKey==intKey );
5943 pCur->ix = (u16)idx;
5944 if( !pPage->leaf ){
5945 lwr = idx;
5946 goto moveto_table_next_layer;
5947 }else{
5948 pCur->curFlags |= BTCF_ValidNKey;
5949 pCur->info.nKey = nCellKey;
5950 pCur->info.nSize = 0;
5951 *pRes = 0;
5952 return SQLITE_OK;
5953 }
5954 }
5955 assert( lwr+upr>=0 );
5956 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
5957 }
5958 assert( lwr==upr+1 || !pPage->leaf );
5959 assert( pPage->isInit );
5960 if( pPage->leaf ){
5961 assert( pCur->ix<pCur->pPage->nCell );
5962 pCur->ix = (u16)idx;
5963 *pRes = c;
5964 rc = SQLITE_OK;
5965 goto moveto_table_finish;
5966 }
5967moveto_table_next_layer:
5968 if( lwr>=pPage->nCell ){
5969 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
5970 }else{
5971 chldPg = get4byte(findCell(pPage, lwr));
5972 }
5973 pCur->ix = (u16)lwr;
5974 rc = moveToChild(pCur, chldPg);
5975 if( rc ) break;
5976 }
5977moveto_table_finish:
5978 pCur->info.nSize = 0;
5979 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
5980 return rc;
5981}
5982
5983/*
5984** Compare the "idx"-th cell on the page pPage against the key
5985** pointing to by pIdxKey using xRecordCompare. Return negative or
5986** zero if the cell is less than or equal pIdxKey. Return positive
5987** if unknown.
5988**
5989** Return value negative: Cell at pPage[idx] less than pIdxKey
5990**
5991** Return value is zero: Cell at pPage[idx] equals pIdxKey
5992**
5993** Return value positive: Nothing is known about the relationship
5994** of the cell at pPage[idx] and pIdxKey.
5995**
5996** This routine is part of an optimization. It is always safe to return
5997** a positive value as that will cause the optimization to be skipped.
5998*/
5999static int indexCellCompare(
6000 MemPage *pPage,
6001 int idx,
6002 UnpackedRecord *pIdxKey,
6003 RecordCompare xRecordCompare
6004){
6005 int c;
6006 int nCell; /* Size of the pCell cell in bytes */
6007 u8 *pCell = findCellPastPtr(pPage, idx);
6008
6009 nCell = pCell[0];
6010 if( nCell<=pPage->max1bytePayload ){
6011 /* This branch runs if the record-size field of the cell is a
6012 ** single byte varint and the record fits entirely on the main
6013 ** b-tree page. */
6014 if( pCell + nCell >= pPage->aDataEnd ) return 99;
6015 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
6016 }else if( !(pCell[1] & 0x80)
6017 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
6018 ){
6019 /* The record-size field is a 2 byte varint and the record
6020 ** fits entirely on the main b-tree page. */
6021 if( pCell + nCell >= pPage->aDataEnd ) return 99;
6022 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
6023 }else{
6024 /* If the record extends into overflow pages, do not attempt
6025 ** the optimization. */
6026 c = 99;
6027 }
6028 return c;
6029}
6030
6031/*
6032** Return true (non-zero) if pCur is current pointing to the last
6033** page of a table.
6034*/
6035static int cursorOnLastPage(BtCursor *pCur){
6036 int i;
6037 assert( pCur->eState==CURSOR_VALID );
6038 for(i=0; i<pCur->iPage; i++){
6039 MemPage *pPage = pCur->apPage[i];
6040 if( pCur->aiIdx[i]<pPage->nCell ) return 0;
6041 }
6042 return 1;
6043}
6044
6045/* Move the cursor so that it points to an entry in an index table
6046** near the key pIdxKey. Return a success code.
6047**
6048** If an exact match is not found, then the cursor is always
6049** left pointing at a leaf page which would hold the entry if it
6050** were present. The cursor might point to an entry that comes
6051** before or after the key.
6052**
6053** An integer is written into *pRes which is the result of
6054** comparing the key with the entry to which the cursor is
6055** pointing. The meaning of the integer written into
6056** *pRes is as follows:
6057**
6058** *pRes<0 The cursor is left pointing at an entry that
6059** is smaller than pIdxKey or if the table is empty
6060** and the cursor is therefore left point to nothing.
6061**
6062** *pRes==0 The cursor is left pointing at an entry that
6063** exactly matches pIdxKey.
6064**
6065** *pRes>0 The cursor is left pointing at an entry that
6066** is larger than pIdxKey.
6067**
6068** The pIdxKey->eqSeen field is set to 1 if there
6069** exists an entry in the table that exactly matches pIdxKey.
6070*/
6071int sqlite3BtreeIndexMoveto(
6072 BtCursor *pCur, /* The cursor to be moved */
6073 UnpackedRecord *pIdxKey, /* Unpacked index key */
6074 int *pRes /* Write search results here */
6075){
6076 int rc;
6077 RecordCompare xRecordCompare;
6078
6079 assert( cursorOwnsBtShared(pCur) );
6080 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
6081 assert( pRes );
6082 assert( pCur->pKeyInfo!=0 );
6083
6084#ifdef SQLITE_DEBUG
6085 pCur->pBtree->nSeek++; /* Performance measurement during testing */
6086#endif
6087
6088 xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
6089 pIdxKey->errCode = 0;
6090 assert( pIdxKey->default_rc==1
6091 || pIdxKey->default_rc==0
6092 || pIdxKey->default_rc==-1
6093 );
6094
6095
6096 /* Check to see if we can skip a lot of work. Two cases:
6097 **
6098 ** (1) If the cursor is already pointing to the very last cell
6099 ** in the table and the pIdxKey search key is greater than or
6100 ** equal to that last cell, then no movement is required.
6101 **
6102 ** (2) If the cursor is on the last page of the table and the first
6103 ** cell on that last page is less than or equal to the pIdxKey
6104 ** search key, then we can start the search on the current page
6105 ** without needing to go back to root.
6106 */
6107 if( pCur->eState==CURSOR_VALID
6108 && pCur->pPage->leaf
6109 && cursorOnLastPage(pCur)
6110 ){
6111 int c;
6112 if( pCur->ix==pCur->pPage->nCell-1
6113 && (c = indexCellCompare(pCur->pPage,pCur->ix,pIdxKey,xRecordCompare))<=0
6114 && pIdxKey->errCode==SQLITE_OK
6115 ){
6116 *pRes = c;
6117 return SQLITE_OK; /* Cursor already pointing at the correct spot */
6118 }
6119 if( pCur->iPage>0
6120 && indexCellCompare(pCur->pPage, 0, pIdxKey, xRecordCompare)<=0
6121 && pIdxKey->errCode==SQLITE_OK
6122 ){
6123 pCur->curFlags &= ~(BTCF_ValidOvfl|BTCF_AtLast);
6124 if( !pCur->pPage->isInit ){
6125 return SQLITE_CORRUPT_BKPT;
6126 }
6127 goto bypass_moveto_root; /* Start search on the current page */
6128 }
6129 pIdxKey->errCode = SQLITE_OK;
6130 }
6131
6132 rc = moveToRoot(pCur);
6133 if( rc ){
6134 if( rc==SQLITE_EMPTY ){
6135 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
6136 *pRes = -1;
6137 return SQLITE_OK;
6138 }
6139 return rc;
6140 }
6141
6142bypass_moveto_root:
6143 assert( pCur->pPage );
6144 assert( pCur->pPage->isInit );
6145 assert( pCur->eState==CURSOR_VALID );
6146 assert( pCur->pPage->nCell > 0 );
6147 assert( pCur->curIntKey==0 );
6148 assert( pIdxKey!=0 );
6149 for(;;){
6150 int lwr, upr, idx, c;
6151 Pgno chldPg;
6152 MemPage *pPage = pCur->pPage;
6153 u8 *pCell; /* Pointer to current cell in pPage */
6154
6155 /* pPage->nCell must be greater than zero. If this is the root-page
6156 ** the cursor would have been INVALID above and this for(;;) loop
6157 ** not run. If this is not the root-page, then the moveToChild() routine
6158 ** would have already detected db corruption. Similarly, pPage must
6159 ** be the right kind (index or table) of b-tree page. Otherwise
6160 ** a moveToChild() or moveToRoot() call would have detected corruption. */
6161 assert( pPage->nCell>0 );
6162 assert( pPage->intKey==0 );
6163 lwr = 0;
6164 upr = pPage->nCell-1;
6165 idx = upr>>1; /* idx = (lwr+upr)/2; */
6166 for(;;){
6167 int nCell; /* Size of the pCell cell in bytes */
6168 pCell = findCellPastPtr(pPage, idx);
6169
6170 /* The maximum supported page-size is 65536 bytes. This means that
6171 ** the maximum number of record bytes stored on an index B-Tree
6172 ** page is less than 16384 bytes and may be stored as a 2-byte
6173 ** varint. This information is used to attempt to avoid parsing
6174 ** the entire cell by checking for the cases where the record is
6175 ** stored entirely within the b-tree page by inspecting the first
6176 ** 2 bytes of the cell.
6177 */
6178 nCell = pCell[0];
6179 if( nCell<=pPage->max1bytePayload ){
6180 /* This branch runs if the record-size field of the cell is a
6181 ** single byte varint and the record fits entirely on the main
6182 ** b-tree page. */
6183 if( pCell + nCell >= pPage->aDataEnd ){
6184 rc = SQLITE_CORRUPT_PAGE(pPage);
6185 goto moveto_index_finish;
6186 }
6187 c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
6188 }else if( !(pCell[1] & 0x80)
6189 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
6190 && pCell + nCell < pPage->aDataEnd
6191 ){
6192 /* The record-size field is a 2 byte varint and the record
6193 ** fits entirely on the main b-tree page. */
6194 c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
6195 }else{
6196 /* The record flows over onto one or more overflow pages. In
6197 ** this case the whole cell needs to be parsed, a buffer allocated
6198 ** and accessPayload() used to retrieve the record into the
6199 ** buffer before VdbeRecordCompare() can be called.
6200 **
6201 ** If the record is corrupt, the xRecordCompare routine may read
6202 ** up to two varints past the end of the buffer. An extra 18
6203 ** bytes of padding is allocated at the end of the buffer in
6204 ** case this happens. */
6205 void *pCellKey;
6206 u8 * const pCellBody = pCell - pPage->childPtrSize;
6207 const int nOverrun = 18; /* Size of the overrun padding */
6208 pPage->xParseCell(pPage, pCellBody, &pCur->info);
6209 nCell = (int)pCur->info.nKey;
6210 testcase( nCell<0 ); /* True if key size is 2^32 or more */
6211 testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
6212 testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
6213 testcase( nCell==2 ); /* Minimum legal index key size */
6214 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
6215 rc = SQLITE_CORRUPT_PAGE(pPage);
6216 goto moveto_index_finish;
6217 }
6218 pCellKey = sqlite3Malloc( (u64)nCell+(u64)nOverrun );
6219 if( pCellKey==0 ){
6220 rc = SQLITE_NOMEM_BKPT;
6221 goto moveto_index_finish;
6222 }
6223 pCur->ix = (u16)idx;
6224 rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
6225 memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
6226 pCur->curFlags &= ~BTCF_ValidOvfl;
6227 if( rc ){
6228 sqlite3_free(pCellKey);
6229 goto moveto_index_finish;
6230 }
6231 c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
6232 sqlite3_free(pCellKey);
6233 }
6234 assert(
6235 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
6236 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
6237 );
6238 if( c<0 ){
6239 lwr = idx+1;
6240 }else if( c>0 ){
6241 upr = idx-1;
6242 }else{
6243 assert( c==0 );
6244 *pRes = 0;
6245 rc = SQLITE_OK;
6246 pCur->ix = (u16)idx;
6247 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
6248 goto moveto_index_finish;
6249 }
6250 if( lwr>upr ) break;
6251 assert( lwr+upr>=0 );
6252 idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
6253 }
6254 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
6255 assert( pPage->isInit );
6256 if( pPage->leaf ){
6257 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
6258 pCur->ix = (u16)idx;
6259 *pRes = c;
6260 rc = SQLITE_OK;
6261 goto moveto_index_finish;
6262 }
6263 if( lwr>=pPage->nCell ){
6264 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
6265 }else{
6266 chldPg = get4byte(findCell(pPage, lwr));
6267 }
6268
6269 /* This block is similar to an in-lined version of:
6270 **
6271 ** pCur->ix = (u16)lwr;
6272 ** rc = moveToChild(pCur, chldPg);
6273 ** if( rc ) break;
6274 */
6275 pCur->info.nSize = 0;
6276 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6277 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
6278 return SQLITE_CORRUPT_BKPT;
6279 }
6280 pCur->aiIdx[pCur->iPage] = (u16)lwr;
6281 pCur->apPage[pCur->iPage] = pCur->pPage;
6282 pCur->ix = 0;
6283 pCur->iPage++;
6284 rc = getAndInitPage(pCur->pBt, chldPg, &pCur->pPage, pCur->curPagerFlags);
6285 if( rc==SQLITE_OK
6286 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
6287 ){
6288 releasePage(pCur->pPage);
6289 rc = SQLITE_CORRUPT_PGNO(chldPg);
6290 }
6291 if( rc ){
6292 pCur->pPage = pCur->apPage[--pCur->iPage];
6293 break;
6294 }
6295 /*
6296 ***** End of in-lined moveToChild() call */
6297 }
6298moveto_index_finish:
6299 pCur->info.nSize = 0;
6300 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6301 return rc;
6302}
6303
6304
6305/*
6306** Return TRUE if the cursor is not pointing at an entry of the table.
6307**
6308** TRUE will be returned after a call to sqlite3BtreeNext() moves
6309** past the last entry in the table or sqlite3BtreePrev() moves past
6310** the first entry. TRUE is also returned if the table is empty.
6311*/
6312int sqlite3BtreeEof(BtCursor *pCur){
6313 /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
6314 ** have been deleted? This API will need to change to return an error code
6315 ** as well as the boolean result value.
6316 */
6317 return (CURSOR_VALID!=pCur->eState);
6318}
6319
6320/*
6321** Return an estimate for the number of rows in the table that pCur is
6322** pointing to. Return a negative number if no estimate is currently
6323** available.
6324*/
6325i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
6326 i64 n;
6327 u8 i;
6328
6329 assert( cursorOwnsBtShared(pCur) );
6330 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
6331
6332 /* Currently this interface is only called by the OP_IfSizeBetween
6333 ** opcode and the OP_Count opcode with P3=1. In either case,
6334 ** the cursor will always be valid unless the btree is empty. */
6335 if( pCur->eState!=CURSOR_VALID ) return 0;
6336 if( NEVER(pCur->pPage->leaf==0) ) return -1;
6337
6338 n = pCur->pPage->nCell;
6339 for(i=0; i<pCur->iPage; i++){
6340 n *= pCur->apPage[i]->nCell+1;
6341 }
6342 return n;
6343}
6344
6345/*
6346** Advance the cursor to the next entry in the database.
6347** Return value:
6348**
6349** SQLITE_OK success
6350** SQLITE_DONE cursor is already pointing at the last element
6351** otherwise some kind of error occurred
6352**
6353** The main entry point is sqlite3BtreeNext(). That routine is optimized
6354** for the common case of merely incrementing the cell counter BtCursor.aiIdx
6355** to the next cell on the current page. The (slower) btreeNext() helper
6356** routine is called when it is necessary to move to a different page or
6357** to restore the cursor.
6358**
6359** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
6360** cursor corresponds to an SQL index and this routine could have been
6361** skipped if the SQL index had been a unique index. The F argument
6362** is a hint to the implement. SQLite btree implementation does not use
6363** this hint, but COMDB2 does.
6364*/
6365static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
6366 int rc;
6367 int idx;
6368 MemPage *pPage;
6369
6370 assert( cursorOwnsBtShared(pCur) );
6371 if( pCur->eState!=CURSOR_VALID ){
6372 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
6373 rc = restoreCursorPosition(pCur);
6374 if( rc!=SQLITE_OK ){
6375 return rc;
6376 }
6377 if( CURSOR_INVALID==pCur->eState ){
6378 return SQLITE_DONE;
6379 }
6380 if( pCur->eState==CURSOR_SKIPNEXT ){
6381 pCur->eState = CURSOR_VALID;
6382 if( pCur->skipNext>0 ) return SQLITE_OK;
6383 }
6384 }
6385
6386 pPage = pCur->pPage;
6387 idx = ++pCur->ix;
6388 if( sqlite3FaultSim(412) ) pPage->isInit = 0;
6389 if( !pPage->isInit ){
6390 return SQLITE_CORRUPT_BKPT;
6391 }
6392
6393 if( idx>=pPage->nCell ){
6394 if( !pPage->leaf ){
6395 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
6396 if( rc ) return rc;
6397 return moveToLeftmost(pCur);
6398 }
6399 do{
6400 if( pCur->iPage==0 ){
6401 pCur->eState = CURSOR_INVALID;
6402 return SQLITE_DONE;
6403 }
6404 moveToParent(pCur);
6405 pPage = pCur->pPage;
6406 }while( pCur->ix>=pPage->nCell );
6407 if( pPage->intKey ){
6408 return sqlite3BtreeNext(pCur, 0);
6409 }else{
6410 return SQLITE_OK;
6411 }
6412 }
6413 if( pPage->leaf ){
6414 return SQLITE_OK;
6415 }else{
6416 return moveToLeftmost(pCur);
6417 }
6418}
6419int sqlite3BtreeNext(BtCursor *pCur, int flags){
6420 MemPage *pPage;
6421 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6422 assert( cursorOwnsBtShared(pCur) );
6423 assert( flags==0 || flags==1 );
6424 pCur->info.nSize = 0;
6425 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
6426 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
6427 pPage = pCur->pPage;
6428 if( (++pCur->ix)>=pPage->nCell ){
6429 pCur->ix--;
6430 return btreeNext(pCur);
6431 }
6432 if( pPage->leaf ){
6433 return SQLITE_OK;
6434 }else{
6435 return moveToLeftmost(pCur);
6436 }
6437}
6438
6439/*
6440** Step the cursor to the back to the previous entry in the database.
6441** Return values:
6442**
6443** SQLITE_OK success
6444** SQLITE_DONE the cursor is already on the first element of the table
6445** otherwise some kind of error occurred
6446**
6447** The main entry point is sqlite3BtreePrevious(). That routine is optimized
6448** for the common case of merely decrementing the cell counter BtCursor.aiIdx
6449** to the previous cell on the current page. The (slower) btreePrevious()
6450** helper routine is called when it is necessary to move to a different page
6451** or to restore the cursor.
6452**
6453** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
6454** the cursor corresponds to an SQL index and this routine could have been
6455** skipped if the SQL index had been a unique index. The F argument is a
6456** hint to the implement. The native SQLite btree implementation does not
6457** use this hint, but COMDB2 does.
6458*/
6459static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
6460 int rc;
6461 MemPage *pPage;
6462
6463 assert( cursorOwnsBtShared(pCur) );
6464 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
6465 assert( pCur->info.nSize==0 );
6466 if( pCur->eState!=CURSOR_VALID ){
6467 rc = restoreCursorPosition(pCur);
6468 if( rc!=SQLITE_OK ){
6469 return rc;
6470 }
6471 if( CURSOR_INVALID==pCur->eState ){
6472 return SQLITE_DONE;
6473 }
6474 if( CURSOR_SKIPNEXT==pCur->eState ){
6475 pCur->eState = CURSOR_VALID;
6476 if( pCur->skipNext<0 ) return SQLITE_OK;
6477 }
6478 }
6479
6480 pPage = pCur->pPage;
6481 if( sqlite3FaultSim(412) ) pPage->isInit = 0;
6482 if( !pPage->isInit ){
6483 return SQLITE_CORRUPT_BKPT;
6484 }
6485 if( !pPage->leaf ){
6486 int idx = pCur->ix;
6487 rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
6488 if( rc ) return rc;
6489 rc = moveToRightmost(pCur);
6490 }else{
6491 while( pCur->ix==0 ){
6492 if( pCur->iPage==0 ){
6493 pCur->eState = CURSOR_INVALID;
6494 return SQLITE_DONE;
6495 }
6496 moveToParent(pCur);
6497 }
6498 assert( pCur->info.nSize==0 );
6499 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
6500
6501 pCur->ix--;
6502 pPage = pCur->pPage;
6503 if( pPage->intKey && !pPage->leaf ){
6504 rc = sqlite3BtreePrevious(pCur, 0);
6505 }else{
6506 rc = SQLITE_OK;
6507 }
6508 }
6509 return rc;
6510}
6511int sqlite3BtreePrevious(BtCursor *pCur, int flags){
6512 assert( cursorOwnsBtShared(pCur) );
6513 assert( flags==0 || flags==1 );
6514 UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
6515 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
6516 pCur->info.nSize = 0;
6517 if( pCur->eState!=CURSOR_VALID
6518 || pCur->ix==0
6519 || pCur->pPage->leaf==0
6520 ){
6521 return btreePrevious(pCur);
6522 }
6523 pCur->ix--;
6524 return SQLITE_OK;
6525}
6526
6527/*
6528** Allocate a new page from the database file.
6529**
6530** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
6531** has already been called on the new page.) The new page has also
6532** been referenced and the calling routine is responsible for calling
6533** sqlite3PagerUnref() on the new page when it is done.
6534**
6535** SQLITE_OK is returned on success. Any other return value indicates
6536** an error. *ppPage is set to NULL in the event of an error.
6537**
6538** If the "nearby" parameter is not 0, then an effort is made to
6539** locate a page close to the page number "nearby". This can be used in an
6540** attempt to keep related pages close to each other in the database file,
6541** which in turn can make database access faster.
6542**
6543** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
6544** anywhere on the free-list, then it is guaranteed to be returned. If
6545** eMode is BTALLOC_LT then the page returned will be less than or equal
6546** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
6547** are no restrictions on which page is returned.
6548*/
6549static int allocateBtreePage(
6550 BtShared *pBt, /* The btree */
6551 MemPage **ppPage, /* Store pointer to the allocated page here */
6552 Pgno *pPgno, /* Store the page number here */
6553 Pgno nearby, /* Search for a page near this one */
6554 u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
6555){
6556 MemPage *pPage1;
6557 int rc;
6558 u32 n; /* Number of pages on the freelist */
6559 u32 k; /* Number of leaves on the trunk of the freelist */
6560 MemPage *pTrunk = 0;
6561 MemPage *pPrevTrunk = 0;
6562 Pgno mxPage; /* Total size of the database file */
6563
6564 assert( sqlite3_mutex_held(pBt->mutex) );
6565 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
6566 pPage1 = pBt->pPage1;
6567 mxPage = btreePagecount(pBt);
6568 /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
6569 ** stores the total number of pages on the freelist. */
6570 n = get4byte(&pPage1->aData[36]);
6571 testcase( n==mxPage-1 );
6572 if( n>=mxPage ){
6573 return SQLITE_CORRUPT_BKPT;
6574 }
6575 if( n>0 ){
6576 /* There are pages on the freelist. Reuse one of those pages. */
6577 Pgno iTrunk;
6578 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
6579 u32 nSearch = 0; /* Count of the number of search attempts */
6580
6581 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
6582 ** shows that the page 'nearby' is somewhere on the free-list, then
6583 ** the entire-list will be searched for that page.
6584 */
6585#ifndef SQLITE_OMIT_AUTOVACUUM
6586 if( eMode==BTALLOC_EXACT ){
6587 if( nearby<=mxPage ){
6588 u8 eType;
6589 assert( nearby>0 );
6590 assert( pBt->autoVacuum );
6591 rc = ptrmapGet(pBt, nearby, &eType, 0);
6592 if( rc ) return rc;
6593 if( eType==PTRMAP_FREEPAGE ){
6594 searchList = 1;
6595 }
6596 }
6597 }else if( eMode==BTALLOC_LE ){
6598 searchList = 1;
6599 }
6600#endif
6601
6602 /* Decrement the free-list count by 1. Set iTrunk to the index of the
6603 ** first free-list trunk page. iPrevTrunk is initially 1.
6604 */
6605 rc = sqlite3PagerWrite(pPage1->pDbPage);
6606 if( rc ) return rc;
6607 put4byte(&pPage1->aData[36], n-1);
6608
6609 /* The code within this loop is run only once if the 'searchList' variable
6610 ** is not true. Otherwise, it runs once for each trunk-page on the
6611 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
6612 ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
6613 */
6614 do {
6615 pPrevTrunk = pTrunk;
6616 if( pPrevTrunk ){
6617 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
6618 ** is the page number of the next freelist trunk page in the list or
6619 ** zero if this is the last freelist trunk page. */
6620 iTrunk = get4byte(&pPrevTrunk->aData[0]);
6621 }else{
6622 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
6623 ** stores the page number of the first page of the freelist, or zero if
6624 ** the freelist is empty. */
6625 iTrunk = get4byte(&pPage1->aData[32]);
6626 }
6627 testcase( iTrunk==mxPage );
6628 if( iTrunk>mxPage || nSearch++ > n ){
6629 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
6630 }else{
6631 rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
6632 }
6633 if( rc ){
6634 pTrunk = 0;
6635 goto end_allocate_page;
6636 }
6637 assert( pTrunk!=0 );
6638 assert( pTrunk->aData!=0 );
6639 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
6640 ** is the number of leaf page pointers to follow. */
6641 k = get4byte(&pTrunk->aData[4]);
6642 if( k==0 && !searchList ){
6643 /* The trunk has no leaves and the list is not being searched.
6644 ** So extract the trunk page itself and use it as the newly
6645 ** allocated page */
6646 assert( pPrevTrunk==0 );
6647 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6648 if( rc ){
6649 goto end_allocate_page;
6650 }
6651 *pPgno = iTrunk;
6652 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6653 *ppPage = pTrunk;
6654 pTrunk = 0;
6655 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6656 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
6657 /* Value of k is out of range. Database corruption */
6658 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6659 goto end_allocate_page;
6660#ifndef SQLITE_OMIT_AUTOVACUUM
6661 }else if( searchList
6662 && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
6663 ){
6664 /* The list is being searched and this trunk page is the page
6665 ** to allocate, regardless of whether it has leaves.
6666 */
6667 *pPgno = iTrunk;
6668 *ppPage = pTrunk;
6669 searchList = 0;
6670 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6671 if( rc ){
6672 goto end_allocate_page;
6673 }
6674 if( k==0 ){
6675 if( !pPrevTrunk ){
6676 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
6677 }else{
6678 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6679 if( rc!=SQLITE_OK ){
6680 goto end_allocate_page;
6681 }
6682 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
6683 }
6684 }else{
6685 /* The trunk page is required by the caller but it contains
6686 ** pointers to free-list leaves. The first leaf becomes a trunk
6687 ** page in this case.
6688 */
6689 MemPage *pNewTrunk;
6690 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
6691 if( iNewTrunk>mxPage ){
6692 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6693 goto end_allocate_page;
6694 }
6695 testcase( iNewTrunk==mxPage );
6696 rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
6697 if( rc!=SQLITE_OK ){
6698 goto end_allocate_page;
6699 }
6700 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
6701 if( rc!=SQLITE_OK ){
6702 releasePage(pNewTrunk);
6703 goto end_allocate_page;
6704 }
6705 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
6706 put4byte(&pNewTrunk->aData[4], k-1);
6707 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
6708 releasePage(pNewTrunk);
6709 if( !pPrevTrunk ){
6710 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
6711 put4byte(&pPage1->aData[32], iNewTrunk);
6712 }else{
6713 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
6714 if( rc ){
6715 goto end_allocate_page;
6716 }
6717 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
6718 }
6719 }
6720 pTrunk = 0;
6721 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
6722#endif
6723 }else if( k>0 ){
6724 /* Extract a leaf from the trunk */
6725 u32 closest;
6726 Pgno iPage;
6727 unsigned char *aData = pTrunk->aData;
6728 if( nearby>0 ){
6729 u32 i;
6730 closest = 0;
6731 if( eMode==BTALLOC_LE ){
6732 for(i=0; i<k; i++){
6733 iPage = get4byte(&aData[8+i*4]);
6734 if( iPage<=nearby ){
6735 closest = i;
6736 break;
6737 }
6738 }
6739 }else{
6740 int dist;
6741 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
6742 for(i=1; i<k; i++){
6743 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
6744 if( d2<dist ){
6745 closest = i;
6746 dist = d2;
6747 }
6748 }
6749 }
6750 }else{
6751 closest = 0;
6752 }
6753
6754 iPage = get4byte(&aData[8+closest*4]);
6755 testcase( iPage==mxPage );
6756 if( iPage>mxPage || iPage<2 ){
6757 rc = SQLITE_CORRUPT_PGNO(iTrunk);
6758 goto end_allocate_page;
6759 }
6760 testcase( iPage==mxPage );
6761 if( !searchList
6762 || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
6763 ){
6764 int noContent;
6765 *pPgno = iPage;
6766 TRACE(("ALLOCATE: %u was leaf %u of %u on trunk %u"
6767 ": %u more free pages\n",
6768 *pPgno, closest+1, k, pTrunk->pgno, n-1));
6769 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6770 if( rc ) goto end_allocate_page;
6771 if( closest<k-1 ){
6772 memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
6773 }
6774 put4byte(&aData[4], k-1);
6775 noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
6776 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
6777 if( rc==SQLITE_OK ){
6778 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6779 if( rc!=SQLITE_OK ){
6780 releasePage(*ppPage);
6781 *ppPage = 0;
6782 }
6783 }
6784 searchList = 0;
6785 }
6786 }
6787 releasePage(pPrevTrunk);
6788 pPrevTrunk = 0;
6789 }while( searchList );
6790 }else{
6791 /* There are no pages on the freelist, so append a new page to the
6792 ** database image.
6793 **
6794 ** Normally, new pages allocated by this block can be requested from the
6795 ** pager layer with the 'no-content' flag set. This prevents the pager
6796 ** from trying to read the pages content from disk. However, if the
6797 ** current transaction has already run one or more incremental-vacuum
6798 ** steps, then the page we are about to allocate may contain content
6799 ** that is required in the event of a rollback. In this case, do
6800 ** not set the no-content flag. This causes the pager to load and journal
6801 ** the current page content before overwriting it.
6802 **
6803 ** Note that the pager will not actually attempt to load or journal
6804 ** content for any page that really does lie past the end of the database
6805 ** file on disk. So the effects of disabling the no-content optimization
6806 ** here are confined to those pages that lie between the end of the
6807 ** database image and the end of the database file.
6808 */
6809 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
6810
6811 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
6812 if( rc ) return rc;
6813 pBt->nPage++;
6814 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
6815
6816#ifndef SQLITE_OMIT_AUTOVACUUM
6817 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
6818 /* If *pPgno refers to a pointer-map page, allocate two new pages
6819 ** at the end of the file instead of one. The first allocated page
6820 ** becomes a new pointer-map page, the second is used by the caller.
6821 */
6822 MemPage *pPg = 0;
6823 TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage));
6824 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
6825 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
6826 if( rc==SQLITE_OK ){
6827 rc = sqlite3PagerWrite(pPg->pDbPage);
6828 releasePage(pPg);
6829 }
6830 if( rc ) return rc;
6831 pBt->nPage++;
6832 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
6833 }
6834#endif
6835 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
6836 *pPgno = pBt->nPage;
6837
6838 assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
6839 rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
6840 if( rc ) return rc;
6841 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
6842 if( rc!=SQLITE_OK ){
6843 releasePage(*ppPage);
6844 *ppPage = 0;
6845 }
6846 TRACE(("ALLOCATE: %u from end of file\n", *pPgno));
6847 }
6848
6849 assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
6850
6851end_allocate_page:
6852 releasePage(pTrunk);
6853 releasePage(pPrevTrunk);
6854 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
6855 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
6856 return rc;
6857}
6858
6859/*
6860** This function is used to add page iPage to the database file free-list.
6861** It is assumed that the page is not already a part of the free-list.
6862**
6863** The value passed as the second argument to this function is optional.
6864** If the caller happens to have a pointer to the MemPage object
6865** corresponding to page iPage handy, it may pass it as the second value.
6866** Otherwise, it may pass NULL.
6867**
6868** If a pointer to a MemPage object is passed as the second argument,
6869** its reference count is not altered by this function.
6870*/
6871static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
6872 MemPage *pTrunk = 0; /* Free-list trunk page */
6873 Pgno iTrunk = 0; /* Page number of free-list trunk page */
6874 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
6875 MemPage *pPage; /* Page being freed. May be NULL. */
6876 int rc; /* Return Code */
6877 u32 nFree; /* Initial number of pages on free-list */
6878
6879 assert( sqlite3_mutex_held(pBt->mutex) );
6880 assert( CORRUPT_DB || iPage>1 );
6881 assert( !pMemPage || pMemPage->pgno==iPage );
6882
6883 if( iPage<2 || iPage>pBt->nPage ){
6884 return SQLITE_CORRUPT_BKPT;
6885 }
6886 if( pMemPage ){
6887 pPage = pMemPage;
6888 sqlite3PagerRef(pPage->pDbPage);
6889 }else{
6890 pPage = btreePageLookup(pBt, iPage);
6891 }
6892
6893 /* Increment the free page count on pPage1 */
6894 rc = sqlite3PagerWrite(pPage1->pDbPage);
6895 if( rc ) goto freepage_out;
6896 nFree = get4byte(&pPage1->aData[36]);
6897 put4byte(&pPage1->aData[36], nFree+1);
6898
6899 if( pBt->btsFlags & BTS_SECURE_DELETE ){
6900 /* If the secure_delete option is enabled, then
6901 ** always fully overwrite deleted information with zeros.
6902 */
6903 if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
6904 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
6905 ){
6906 goto freepage_out;
6907 }
6908 memset(pPage->aData, 0, pPage->pBt->pageSize);
6909 }
6910
6911 /* If the database supports auto-vacuum, write an entry in the pointer-map
6912 ** to indicate that the page is free.
6913 */
6914 if( ISAUTOVACUUM(pBt) ){
6915 ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
6916 if( rc ) goto freepage_out;
6917 }
6918
6919 /* Now manipulate the actual database free-list structure. There are two
6920 ** possibilities. If the free-list is currently empty, or if the first
6921 ** trunk page in the free-list is full, then this page will become a
6922 ** new free-list trunk page. Otherwise, it will become a leaf of the
6923 ** first trunk page in the current free-list. This block tests if it
6924 ** is possible to add the page as a new free-list leaf.
6925 */
6926 if( nFree!=0 ){
6927 u32 nLeaf; /* Initial number of leaf cells on trunk page */
6928
6929 iTrunk = get4byte(&pPage1->aData[32]);
6930 if( iTrunk>btreePagecount(pBt) ){
6931 rc = SQLITE_CORRUPT_BKPT;
6932 goto freepage_out;
6933 }
6934 rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
6935 if( rc!=SQLITE_OK ){
6936 goto freepage_out;
6937 }
6938
6939 nLeaf = get4byte(&pTrunk->aData[4]);
6940 assert( pBt->usableSize>32 );
6941 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
6942 rc = SQLITE_CORRUPT_BKPT;
6943 goto freepage_out;
6944 }
6945 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
6946 /* In this case there is room on the trunk page to insert the page
6947 ** being freed as a new leaf.
6948 **
6949 ** Note that the trunk page is not really full until it contains
6950 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
6951 ** coded. But due to a coding error in versions of SQLite prior to
6952 ** 3.6.0, databases with freelist trunk pages holding more than
6953 ** usableSize/4 - 8 entries will be reported as corrupt. In order
6954 ** to maintain backwards compatibility with older versions of SQLite,
6955 ** we will continue to restrict the number of entries to usableSize/4 - 8
6956 ** for now. At some point in the future (once everyone has upgraded
6957 ** to 3.6.0 or later) we should consider fixing the conditional above
6958 ** to read "usableSize/4-2" instead of "usableSize/4-8".
6959 **
6960 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
6961 ** avoid using the last six entries in the freelist trunk page array in
6962 ** order that database files created by newer versions of SQLite can be
6963 ** read by older versions of SQLite.
6964 */
6965 rc = sqlite3PagerWrite(pTrunk->pDbPage);
6966 if( rc==SQLITE_OK ){
6967 put4byte(&pTrunk->aData[4], nLeaf+1);
6968 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
6969 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
6970 sqlite3PagerDontWrite(pPage->pDbPage);
6971 }
6972 rc = btreeSetHasContent(pBt, iPage);
6973 }
6974 TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno));
6975 goto freepage_out;
6976 }
6977 }
6978
6979 /* If control flows to this point, then it was not possible to add the
6980 ** the page being freed as a leaf page of the first trunk in the free-list.
6981 ** Possibly because the free-list is empty, or possibly because the
6982 ** first trunk in the free-list is full. Either way, the page being freed
6983 ** will become the new first trunk page in the free-list.
6984 */
6985 if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
6986 goto freepage_out;
6987 }
6988 rc = sqlite3PagerWrite(pPage->pDbPage);
6989 if( rc!=SQLITE_OK ){
6990 goto freepage_out;
6991 }
6992 put4byte(pPage->aData, iTrunk);
6993 put4byte(&pPage->aData[4], 0);
6994 put4byte(&pPage1->aData[32], iPage);
6995 TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk));
6996
6997freepage_out:
6998 if( pPage ){
6999 pPage->isInit = 0;
7000 }
7001 releasePage(pPage);
7002 releasePage(pTrunk);
7003 return rc;
7004}
7005static void freePage(MemPage *pPage, int *pRC){
7006 if( (*pRC)==SQLITE_OK ){
7007 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
7008 }
7009}
7010
7011/*
7012** Free the overflow pages associated with the given Cell.
7013*/
7014static SQLITE_NOINLINE int clearCellOverflow(
7015 MemPage *pPage, /* The page that contains the Cell */
7016 unsigned char *pCell, /* First byte of the Cell */
7017 CellInfo *pInfo /* Size information about the cell */
7018){
7019 BtShared *pBt;
7020 Pgno ovflPgno;
7021 int rc;
7022 int nOvfl;
7023 u32 ovflPageSize;
7024
7025 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7026 assert( pInfo->nLocal!=pInfo->nPayload );
7027 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
7028 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
7029 if( pCell + pInfo->nSize > pPage->aDataEnd ){
7030 /* Cell extends past end of page */
7031 return SQLITE_CORRUPT_PAGE(pPage);
7032 }
7033 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
7034 pBt = pPage->pBt;
7035 assert( pBt->usableSize > 4 );
7036 ovflPageSize = pBt->usableSize - 4;
7037 nOvfl = (pInfo->nPayload - pInfo->nLocal + (u64)ovflPageSize-1)/ovflPageSize;
7038 assert( nOvfl>0 );
7039 while( nOvfl-- ){
7040 Pgno iNext = 0;
7041 MemPage *pOvfl = 0;
7042 if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
7043 /* 0 is not a legal page number and page 1 cannot be an
7044 ** overflow page. Therefore if ovflPgno<2 or past the end of the
7045 ** file the database must be corrupt. */
7046 return SQLITE_CORRUPT_BKPT;
7047 }
7048 if( nOvfl ){
7049 rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
7050 if( rc ) return rc;
7051 }
7052
7053 if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
7054 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
7055 ){
7056 /* There is no reason any cursor should have an outstanding reference
7057 ** to an overflow page belonging to a cell that is being deleted/updated.
7058 ** So if there exists more than one reference to this page, then it
7059 ** must not really be an overflow page and the database must be corrupt.
7060 ** It is helpful to detect this before calling freePage2(), as
7061 ** freePage2() may zero the page contents if secure-delete mode is
7062 ** enabled. If this 'overflow' page happens to be a page that the
7063 ** caller is iterating through or using in some other way, this
7064 ** can be problematic.
7065 */
7066 rc = SQLITE_CORRUPT_BKPT;
7067 }else{
7068 rc = freePage2(pBt, pOvfl, ovflPgno);
7069 }
7070
7071 if( pOvfl ){
7072 sqlite3PagerUnref(pOvfl->pDbPage);
7073 }
7074 if( rc ) return rc;
7075 ovflPgno = iNext;
7076 }
7077 return SQLITE_OK;
7078}
7079
7080/* Call xParseCell to compute the size of a cell. If the cell contains
7081** overflow, then invoke cellClearOverflow to clear out that overflow.
7082** Store the result code (SQLITE_OK or some error code) in rc.
7083**
7084** Implemented as macro to force inlining for performance.
7085*/
7086#define BTREE_CLEAR_CELL(rc, pPage, pCell, sInfo) \
7087 pPage->xParseCell(pPage, pCell, &sInfo); \
7088 if( sInfo.nLocal!=sInfo.nPayload ){ \
7089 rc = clearCellOverflow(pPage, pCell, &sInfo); \
7090 }else{ \
7091 rc = SQLITE_OK; \
7092 }
7093
7094
7095/*
7096** Create the byte sequence used to represent a cell on page pPage
7097** and write that byte sequence into pCell[]. Overflow pages are
7098** allocated and filled in as necessary. The calling procedure
7099** is responsible for making sure sufficient space has been allocated
7100** for pCell[].
7101**
7102** Note that pCell does not necessary need to point to the pPage->aData
7103** area. pCell might point to some temporary storage. The cell will
7104** be constructed in this temporary area then copied into pPage->aData
7105** later.
7106*/
7107static int fillInCell(
7108 MemPage *pPage, /* The page that contains the cell */
7109 unsigned char *pCell, /* Complete text of the cell */
7110 const BtreePayload *pX, /* Payload with which to construct the cell */
7111 int *pnSize /* Write cell size here */
7112){
7113 int nPayload;
7114 const u8 *pSrc;
7115 int nSrc, n, rc, mn;
7116 int spaceLeft;
7117 MemPage *pToRelease;
7118 unsigned char *pPrior;
7119 unsigned char *pPayload;
7120 BtShared *pBt;
7121 Pgno pgnoOvfl;
7122 int nHeader;
7123
7124 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7125
7126 /* pPage is not necessarily writeable since pCell might be auxiliary
7127 ** buffer space that is separate from the pPage buffer area */
7128 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
7129 || sqlite3PagerIswriteable(pPage->pDbPage) );
7130
7131 /* Fill in the header. */
7132 nHeader = pPage->childPtrSize;
7133 if( pPage->intKey ){
7134 nPayload = pX->nData + pX->nZero;
7135 pSrc = pX->pData;
7136 nSrc = pX->nData;
7137 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
7138 nHeader += putVarint32(&pCell[nHeader], nPayload);
7139 nHeader += sqlite3PutVarint(&pCell[nHeader], *(u64*)&pX->nKey);
7140 }else{
7141 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
7142 nSrc = nPayload = (int)pX->nKey;
7143 pSrc = pX->pKey;
7144 nHeader += putVarint32(&pCell[nHeader], nPayload);
7145 }
7146
7147 /* Fill in the payload */
7148 pPayload = &pCell[nHeader];
7149 if( nPayload<=pPage->maxLocal ){
7150 /* This is the common case where everything fits on the btree page
7151 ** and no overflow pages are required. */
7152 n = nHeader + nPayload;
7153 testcase( n==3 );
7154 testcase( n==4 );
7155 if( n<4 ){
7156 n = 4;
7157 pPayload[nPayload] = 0;
7158 }
7159 *pnSize = n;
7160 assert( nSrc<=nPayload );
7161 testcase( nSrc<nPayload );
7162 memcpy(pPayload, pSrc, nSrc);
7163 memset(pPayload+nSrc, 0, nPayload-nSrc);
7164 return SQLITE_OK;
7165 }
7166
7167 /* If we reach this point, it means that some of the content will need
7168 ** to spill onto overflow pages.
7169 */
7170 mn = pPage->minLocal;
7171 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
7172 testcase( n==pPage->maxLocal );
7173 testcase( n==pPage->maxLocal+1 );
7174 if( n > pPage->maxLocal ) n = mn;
7175 spaceLeft = n;
7176 *pnSize = n + nHeader + 4;
7177 pPrior = &pCell[nHeader+n];
7178 pToRelease = 0;
7179 pgnoOvfl = 0;
7180 pBt = pPage->pBt;
7181
7182 /* At this point variables should be set as follows:
7183 **
7184 ** nPayload Total payload size in bytes
7185 ** pPayload Begin writing payload here
7186 ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
7187 ** that means content must spill into overflow pages.
7188 ** *pnSize Size of the local cell (not counting overflow pages)
7189 ** pPrior Where to write the pgno of the first overflow page
7190 **
7191 ** Use a call to btreeParseCellPtr() to verify that the values above
7192 ** were computed correctly.
7193 */
7194#ifdef SQLITE_DEBUG
7195 {
7196 CellInfo info;
7197 pPage->xParseCell(pPage, pCell, &info);
7198 assert( nHeader==(int)(info.pPayload - pCell) );
7199 assert( info.nKey==pX->nKey );
7200 assert( *pnSize == info.nSize );
7201 assert( spaceLeft == info.nLocal );
7202 }
7203#endif
7204
7205 /* Write the payload into the local Cell and any extra into overflow pages */
7206 while( 1 ){
7207 n = nPayload;
7208 if( n>spaceLeft ) n = spaceLeft;
7209
7210 /* If pToRelease is not zero than pPayload points into the data area
7211 ** of pToRelease. Make sure pToRelease is still writeable. */
7212 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7213
7214 /* If pPayload is part of the data area of pPage, then make sure pPage
7215 ** is still writeable */
7216 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
7217 || sqlite3PagerIswriteable(pPage->pDbPage) );
7218
7219 if( nSrc>=n ){
7220 memcpy(pPayload, pSrc, n);
7221 }else if( nSrc>0 ){
7222 n = nSrc;
7223 memcpy(pPayload, pSrc, n);
7224 }else{
7225 memset(pPayload, 0, n);
7226 }
7227 nPayload -= n;
7228 if( nPayload<=0 ) break;
7229 pPayload += n;
7230 pSrc += n;
7231 nSrc -= n;
7232 spaceLeft -= n;
7233 if( spaceLeft==0 ){
7234 MemPage *pOvfl = 0;
7235#ifndef SQLITE_OMIT_AUTOVACUUM
7236 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
7237 if( pBt->autoVacuum ){
7238 do{
7239 pgnoOvfl++;
7240 } while(
7241 PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
7242 );
7243 }
7244#endif
7245 rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
7246#ifndef SQLITE_OMIT_AUTOVACUUM
7247 /* If the database supports auto-vacuum, and the second or subsequent
7248 ** overflow page is being allocated, add an entry to the pointer-map
7249 ** for that page now.
7250 **
7251 ** If this is the first overflow page, then write a partial entry
7252 ** to the pointer-map. If we write nothing to this pointer-map slot,
7253 ** then the optimistic overflow chain processing in clearCell()
7254 ** may misinterpret the uninitialized values and delete the
7255 ** wrong pages from the database.
7256 */
7257 if( pBt->autoVacuum && rc==SQLITE_OK ){
7258 u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
7259 ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
7260 if( rc ){
7261 releasePage(pOvfl);
7262 }
7263 }
7264#endif
7265 if( rc ){
7266 releasePage(pToRelease);
7267 return rc;
7268 }
7269
7270 /* If pToRelease is not zero than pPrior points into the data area
7271 ** of pToRelease. Make sure pToRelease is still writeable. */
7272 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
7273
7274 /* If pPrior is part of the data area of pPage, then make sure pPage
7275 ** is still writeable */
7276 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
7277 || sqlite3PagerIswriteable(pPage->pDbPage) );
7278
7279 put4byte(pPrior, pgnoOvfl);
7280 releasePage(pToRelease);
7281 pToRelease = pOvfl;
7282 pPrior = pOvfl->aData;
7283 put4byte(pPrior, 0);
7284 pPayload = &pOvfl->aData[4];
7285 spaceLeft = pBt->usableSize - 4;
7286 }
7287 }
7288 releasePage(pToRelease);
7289 return SQLITE_OK;
7290}
7291
7292/*
7293** Remove the i-th cell from pPage. This routine effects pPage only.
7294** The cell content is not freed or deallocated. It is assumed that
7295** the cell content has been copied someplace else. This routine just
7296** removes the reference to the cell from pPage.
7297**
7298** "sz" must be the number of bytes in the cell.
7299*/
7300static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
7301 u32 pc; /* Offset to cell content of cell being deleted */
7302 u8 *data; /* pPage->aData */
7303 u8 *ptr; /* Used to move bytes around within data[] */
7304 int rc; /* The return code */
7305 int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
7306
7307 if( *pRC ) return;
7308 assert( idx>=0 );
7309 assert( idx<pPage->nCell );
7310 assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
7311 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7312 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7313 assert( pPage->nFree>=0 );
7314 data = pPage->aData;
7315 ptr = &pPage->aCellIdx[2*idx];
7316 assert( pPage->pBt->usableSize > (u32)(ptr-data) );
7317 pc = get2byte(ptr);
7318 hdr = pPage->hdrOffset;
7319 testcase( pc==(u32)get2byte(&data[hdr+5]) );
7320 testcase( pc+sz==pPage->pBt->usableSize );
7321 if( pc+sz > pPage->pBt->usableSize ){
7322 *pRC = SQLITE_CORRUPT_BKPT;
7323 return;
7324 }
7325 rc = freeSpace(pPage, pc, sz);
7326 if( rc ){
7327 *pRC = rc;
7328 return;
7329 }
7330 pPage->nCell--;
7331 if( pPage->nCell==0 ){
7332 memset(&data[hdr+1], 0, 4);
7333 data[hdr+7] = 0;
7334 put2byte(&data[hdr+5], pPage->pBt->usableSize);
7335 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
7336 - pPage->childPtrSize - 8;
7337 }else{
7338 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
7339 put2byte(&data[hdr+3], pPage->nCell);
7340 pPage->nFree += 2;
7341 }
7342}
7343
7344/*
7345** Insert a new cell on pPage at cell index "i". pCell points to the
7346** content of the cell.
7347**
7348** If the cell content will fit on the page, then put it there. If it
7349** will not fit, then make a copy of the cell content into pTemp if
7350** pTemp is not null. Regardless of pTemp, allocate a new entry
7351** in pPage->apOvfl[] and make it point to the cell content (either
7352** in pTemp or the original pCell) and also record its index.
7353** Allocating a new entry in pPage->aCell[] implies that
7354** pPage->nOverflow is incremented.
7355**
7356** The insertCellFast() routine below works exactly the same as
7357** insertCell() except that it lacks the pTemp and iChild parameters
7358** which are assumed zero. Other than that, the two routines are the
7359** same.
7360**
7361** Fixes or enhancements to this routine should be reflected in
7362** insertCellFast()!
7363*/
7364static int insertCell(
7365 MemPage *pPage, /* Page into which we are copying */
7366 int i, /* New cell becomes the i-th cell of the page */
7367 u8 *pCell, /* Content of the new cell */
7368 int sz, /* Bytes of content in pCell */
7369 u8 *pTemp, /* Temp storage space for pCell, if needed */
7370 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
7371){
7372 int idx = 0; /* Where to write new cell content in data[] */
7373 int j; /* Loop counter */
7374 u8 *data; /* The content of the whole page */
7375 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7376
7377 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7378 assert( MX_CELL(pPage->pBt)<=10921 );
7379 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7380 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7381 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7382 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7383 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7384 assert( pPage->nFree>=0 );
7385 assert( iChild>0 );
7386 if( pPage->nOverflow || sz+2>pPage->nFree ){
7387 if( pTemp ){
7388 memcpy(pTemp, pCell, sz);
7389 pCell = pTemp;
7390 }
7391 put4byte(pCell, iChild);
7392 j = pPage->nOverflow++;
7393 /* Comparison against ArraySize-1 since we hold back one extra slot
7394 ** as a contingency. In other words, never need more than 3 overflow
7395 ** slots but 4 are allocated, just to be safe. */
7396 assert( j < ArraySize(pPage->apOvfl)-1 );
7397 pPage->apOvfl[j] = pCell;
7398 pPage->aiOvfl[j] = (u16)i;
7399
7400 /* When multiple overflows occur, they are always sequential and in
7401 ** sorted order. This invariants arise because multiple overflows can
7402 ** only occur when inserting divider cells into the parent page during
7403 ** balancing, and the dividers are adjacent and sorted.
7404 */
7405 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7406 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7407 }else{
7408 int rc = sqlite3PagerWrite(pPage->pDbPage);
7409 if( NEVER(rc!=SQLITE_OK) ){
7410 return rc;
7411 }
7412 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7413 data = pPage->aData;
7414 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7415 rc = allocateSpace(pPage, sz, &idx);
7416 if( rc ){ return rc; }
7417 /* The allocateSpace() routine guarantees the following properties
7418 ** if it returns successfully */
7419 assert( idx >= 0 );
7420 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7421 assert( idx+sz <= (int)pPage->pBt->usableSize );
7422 pPage->nFree -= (u16)(2 + sz);
7423 /* In a corrupt database where an entry in the cell index section of
7424 ** a btree page has a value of 3 or less, the pCell value might point
7425 ** as many as 4 bytes in front of the start of the aData buffer for
7426 ** the source page. Make sure this does not cause problems by not
7427 ** reading the first 4 bytes */
7428 memcpy(&data[idx+4], pCell+4, sz-4);
7429 put4byte(&data[idx], iChild);
7430 pIns = pPage->aCellIdx + i*2;
7431 if( i<pPage->nCell ) memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7432 put2byte(pIns, idx);
7433 pPage->nCell++;
7434 /* increment the cell count */
7435 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7436 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7437#ifndef SQLITE_OMIT_AUTOVACUUM
7438 if( pPage->pBt->autoVacuum ){
7439 int rc2 = SQLITE_OK;
7440 /* The cell may contain a pointer to an overflow page. If so, write
7441 ** the entry for the overflow page into the pointer map.
7442 */
7443 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7444 if( rc2 ) return rc2;
7445 }
7446#endif
7447 }
7448 return SQLITE_OK;
7449}
7450
7451/*
7452** This variant of insertCell() assumes that the pTemp and iChild
7453** parameters are both zero. Use this variant in sqlite3BtreeInsert()
7454** for performance improvement, and also so that this variant is only
7455** called from that one place, and is thus inlined, and thus runs must
7456** faster.
7457**
7458** Fixes or enhancements to this routine should be reflected into
7459** the insertCell() routine.
7460*/
7461static int insertCellFast(
7462 MemPage *pPage, /* Page into which we are copying */
7463 int i, /* New cell becomes the i-th cell of the page */
7464 u8 *pCell, /* Content of the new cell */
7465 int sz /* Bytes of content in pCell */
7466){
7467 int idx = 0; /* Where to write new cell content in data[] */
7468 int j; /* Loop counter */
7469 u8 *data; /* The content of the whole page */
7470 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
7471
7472 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
7473 assert( MX_CELL(pPage->pBt)<=10921 );
7474 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
7475 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
7476 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
7477 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
7478 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
7479 assert( pPage->nFree>=0 );
7480 assert( pPage->nOverflow==0 );
7481 if( sz+2>pPage->nFree ){
7482 j = pPage->nOverflow++;
7483 /* Comparison against ArraySize-1 since we hold back one extra slot
7484 ** as a contingency. In other words, never need more than 3 overflow
7485 ** slots but 4 are allocated, just to be safe. */
7486 assert( j < ArraySize(pPage->apOvfl)-1 );
7487 pPage->apOvfl[j] = pCell;
7488 pPage->aiOvfl[j] = (u16)i;
7489
7490 /* When multiple overflows occur, they are always sequential and in
7491 ** sorted order. This invariants arise because multiple overflows can
7492 ** only occur when inserting divider cells into the parent page during
7493 ** balancing, and the dividers are adjacent and sorted.
7494 */
7495 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
7496 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
7497 }else{
7498 int rc = sqlite3PagerWrite(pPage->pDbPage);
7499 if( rc!=SQLITE_OK ){
7500 return rc;
7501 }
7502 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
7503 data = pPage->aData;
7504 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
7505 rc = allocateSpace(pPage, sz, &idx);
7506 if( rc ){ return rc; }
7507 /* The allocateSpace() routine guarantees the following properties
7508 ** if it returns successfully */
7509 assert( idx >= 0 );
7510 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
7511 assert( idx+sz <= (int)pPage->pBt->usableSize );
7512 pPage->nFree -= (u16)(2 + sz);
7513 memcpy(&data[idx], pCell, sz);
7514 pIns = pPage->aCellIdx + i*2;
7515 if( i<pPage->nCell ) memmove(pIns+2, pIns, 2*(pPage->nCell - i));
7516 put2byte(pIns, idx);
7517 pPage->nCell++;
7518 /* increment the cell count */
7519 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
7520 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
7521#ifndef SQLITE_OMIT_AUTOVACUUM
7522 if( pPage->pBt->autoVacuum ){
7523 int rc2 = SQLITE_OK;
7524 /* The cell may contain a pointer to an overflow page. If so, write
7525 ** the entry for the overflow page into the pointer map.
7526 */
7527 ptrmapPutOvflPtr(pPage, pPage, pCell, &rc2);
7528 if( rc2 ) return rc2;
7529 }
7530#endif
7531 }
7532 return SQLITE_OK;
7533}
7534
7535/*
7536** The following parameters determine how many adjacent pages get involved
7537** in a balancing operation. NN is the number of neighbors on either side
7538** of the page that participate in the balancing operation. NB is the
7539** total number of pages that participate, including the target page and
7540** NN neighbors on either side.
7541**
7542** The minimum value of NN is 1 (of course). Increasing NN above 1
7543** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
7544** in exchange for a larger degradation in INSERT and UPDATE performance.
7545** The value of NN appears to give the best results overall.
7546**
7547** (Later:) The description above makes it seem as if these values are
7548** tunable - as if you could change them and recompile and it would all work.
7549** But that is unlikely. NB has been 3 since the inception of SQLite and
7550** we have never tested any other value.
7551*/
7552#define NN 1 /* Number of neighbors on either side of pPage */
7553#define NB 3 /* (NN*2+1): Total pages involved in the balance */
7554
7555/*
7556** A CellArray object contains a cache of pointers and sizes for a
7557** consecutive sequence of cells that might be held on multiple pages.
7558**
7559** The cells in this array are the divider cell or cells from the pParent
7560** page plus up to three child pages. There are a total of nCell cells.
7561**
7562** pRef is a pointer to one of the pages that contributes cells. This is
7563** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
7564** which should be common to all pages that contribute cells to this array.
7565**
7566** apCell[] and szCell[] hold, respectively, pointers to the start of each
7567** cell and the size of each cell. Some of the apCell[] pointers might refer
7568** to overflow cells. In other words, some apCel[] pointers might not point
7569** to content area of the pages.
7570**
7571** A szCell[] of zero means the size of that cell has not yet been computed.
7572**
7573** The cells come from as many as four different pages:
7574**
7575** -----------
7576** | Parent |
7577** -----------
7578** / | \
7579** / | \
7580** --------- --------- ---------
7581** |Child-1| |Child-2| |Child-3|
7582** --------- --------- ---------
7583**
7584** The order of cells is in the array is for an index btree is:
7585**
7586** 1. All cells from Child-1 in order
7587** 2. The first divider cell from Parent
7588** 3. All cells from Child-2 in order
7589** 4. The second divider cell from Parent
7590** 5. All cells from Child-3 in order
7591**
7592** For a table-btree (with rowids) the items 2 and 4 are empty because
7593** content exists only in leaves and there are no divider cells.
7594**
7595** For an index btree, the apEnd[] array holds pointer to the end of page
7596** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
7597** respectively. The ixNx[] array holds the number of cells contained in
7598** each of these 5 stages, and all stages to the left. Hence:
7599**
7600** ixNx[0] = Number of cells in Child-1.
7601** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
7602** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
7603** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
7604** ixNx[4] = Total number of cells.
7605**
7606** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
7607** are used and they point to the leaf pages only, and the ixNx value are:
7608**
7609** ixNx[0] = Number of cells in Child-1.
7610** ixNx[1] = Number of cells in Child-1 and Child-2.
7611** ixNx[2] = Total number of cells.
7612**
7613** Sometimes when deleting, a child page can have zero cells. In those
7614** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
7615** entries, shift down. The end result is that each ixNx[] entry should
7616** be larger than the previous
7617*/
7618typedef struct CellArray CellArray;
7619struct CellArray {
7620 int nCell; /* Number of cells in apCell[] */
7621 MemPage *pRef; /* Reference page */
7622 u8 **apCell; /* All cells begin balanced */
7623 u16 *szCell; /* Local size of all cells in apCell[] */
7624 u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
7625 int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
7626};
7627
7628/*
7629** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
7630** computed.
7631*/
7632static void populateCellCache(CellArray *p, int idx, int N){
7633 MemPage *pRef = p->pRef;
7634 u16 *szCell = p->szCell;
7635 assert( idx>=0 && idx+N<=p->nCell );
7636 while( N>0 ){
7637 assert( p->apCell[idx]!=0 );
7638 if( szCell[idx]==0 ){
7639 szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]);
7640 }else{
7641 assert( CORRUPT_DB ||
7642 szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) );
7643 }
7644 idx++;
7645 N--;
7646 }
7647}
7648
7649/*
7650** Return the size of the Nth element of the cell array
7651*/
7652static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
7653 assert( N>=0 && N<p->nCell );
7654 assert( p->szCell[N]==0 );
7655 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
7656 return p->szCell[N];
7657}
7658static u16 cachedCellSize(CellArray *p, int N){
7659 assert( N>=0 && N<p->nCell );
7660 if( p->szCell[N] ) return p->szCell[N];
7661 return computeCellSize(p, N);
7662}
7663
7664/*
7665** Array apCell[] contains pointers to nCell b-tree page cells. The
7666** szCell[] array contains the size in bytes of each cell. This function
7667** replaces the current contents of page pPg with the contents of the cell
7668** array.
7669**
7670** Some of the cells in apCell[] may currently be stored in pPg. This
7671** function works around problems caused by this by making a copy of any
7672** such cells before overwriting the page data.
7673**
7674** The MemPage.nFree field is invalidated by this function. It is the
7675** responsibility of the caller to set it correctly.
7676*/
7677static int rebuildPage(
7678 CellArray *pCArray, /* Content to be added to page pPg */
7679 int iFirst, /* First cell in pCArray to use */
7680 int nCell, /* Final number of cells on page */
7681 MemPage *pPg /* The page to be reconstructed */
7682){
7683 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
7684 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
7685 const int usableSize = pPg->pBt->usableSize;
7686 u8 * const pEnd = &aData[usableSize];
7687 int i = iFirst; /* Which cell to copy from pCArray*/
7688 u32 j; /* Start of cell content area */
7689 int iEnd = i+nCell; /* Loop terminator */
7690 u8 *pCellptr = pPg->aCellIdx;
7691 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7692 u8 *pData;
7693 int k; /* Current slot in pCArray->apEnd[] */
7694 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
7695
7696 assert( nCell>0 );
7697 assert( i<iEnd );
7698 j = get2byte(&aData[hdr+5]);
7699 if( j>(u32)usableSize ){ j = 0; }
7700 memcpy(&pTmp[j], &aData[j], usableSize - j);
7701
7702 assert( pCArray->ixNx[NB*2-1]>i );
7703 for(k=0; pCArray->ixNx[k]<=i; k++){}
7704 pSrcEnd = pCArray->apEnd[k];
7705
7706 pData = pEnd;
7707 while( 1/*exit by break*/ ){
7708 u8 *pCell = pCArray->apCell[i];
7709 u16 sz = pCArray->szCell[i];
7710 assert( sz>0 );
7711 if( SQLITE_WITHIN(pCell,aData+j,pEnd) ){
7712 if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
7713 pCell = &pTmp[pCell - aData];
7714 }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
7715 && (uptr)(pCell)<(uptr)pSrcEnd
7716 ){
7717 return SQLITE_CORRUPT_BKPT;
7718 }
7719
7720 pData -= sz;
7721 put2byte(pCellptr, (pData - aData));
7722 pCellptr += 2;
7723 if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
7724 memmove(pData, pCell, sz);
7725 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
7726 i++;
7727 if( i>=iEnd ) break;
7728 if( pCArray->ixNx[k]<=i ){
7729 k++;
7730 pSrcEnd = pCArray->apEnd[k];
7731 }
7732 }
7733
7734 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
7735 assert( nCell < 10922 );
7736 pPg->nCell = (u16)nCell;
7737 pPg->nOverflow = 0;
7738
7739 put2byte(&aData[hdr+1], 0);
7740 put2byte(&aData[hdr+3], pPg->nCell);
7741 put2byte(&aData[hdr+5], pData - aData);
7742 aData[hdr+7] = 0x00;
7743 return SQLITE_OK;
7744}
7745
7746/*
7747** The pCArray objects contains pointers to b-tree cells and the cell sizes.
7748** This function attempts to add the cells stored in the array to page pPg.
7749** If it cannot (because the page needs to be defragmented before the cells
7750** will fit), non-zero is returned. Otherwise, if the cells are added
7751** successfully, zero is returned.
7752**
7753** Argument pCellptr points to the first entry in the cell-pointer array
7754** (part of page pPg) to populate. After cell apCell[0] is written to the
7755** page body, a 16-bit offset is written to pCellptr. And so on, for each
7756** cell in the array. It is the responsibility of the caller to ensure
7757** that it is safe to overwrite this part of the cell-pointer array.
7758**
7759** When this function is called, *ppData points to the start of the
7760** content area on page pPg. If the size of the content area is extended,
7761** *ppData is updated to point to the new start of the content area
7762** before returning.
7763**
7764** Finally, argument pBegin points to the byte immediately following the
7765** end of the space required by this page for the cell-pointer area (for
7766** all cells - not just those inserted by the current call). If the content
7767** area must be extended to before this point in order to accommodate all
7768** cells in apCell[], then the cells do not fit and non-zero is returned.
7769*/
7770static int pageInsertArray(
7771 MemPage *pPg, /* Page to add cells to */
7772 u8 *pBegin, /* End of cell-pointer array */
7773 u8 **ppData, /* IN/OUT: Page content-area pointer */
7774 u8 *pCellptr, /* Pointer to cell-pointer area */
7775 int iFirst, /* Index of first cell to add */
7776 int nCell, /* Number of cells to add to pPg */
7777 CellArray *pCArray /* Array of cells */
7778){
7779 int i = iFirst; /* Loop counter - cell index to insert */
7780 u8 *aData = pPg->aData; /* Complete page */
7781 u8 *pData = *ppData; /* Content area. A subset of aData[] */
7782 int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
7783 int k; /* Current slot in pCArray->apEnd[] */
7784 u8 *pEnd; /* Maximum extent of cell data */
7785 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
7786 if( iEnd<=iFirst ) return 0;
7787 assert( pCArray->ixNx[NB*2-1]>i );
7788 for(k=0; pCArray->ixNx[k]<=i ; k++){}
7789 pEnd = pCArray->apEnd[k];
7790 while( 1 /*Exit by break*/ ){
7791 int sz, rc;
7792 u8 *pSlot;
7793 assert( pCArray->szCell[i]!=0 );
7794 sz = pCArray->szCell[i];
7795 if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
7796 if( (pData - pBegin)<sz ) return 1;
7797 pData -= sz;
7798 pSlot = pData;
7799 }
7800 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
7801 ** database. But they might for a corrupt database. Hence use memmove()
7802 ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
7803 assert( (pSlot+sz)<=pCArray->apCell[i]
7804 || pSlot>=(pCArray->apCell[i]+sz)
7805 || CORRUPT_DB );
7806 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
7807 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
7808 ){
7809 assert( CORRUPT_DB );
7810 (void)SQLITE_CORRUPT_BKPT;
7811 return 1;
7812 }
7813 memmove(pSlot, pCArray->apCell[i], sz);
7814 put2byte(pCellptr, (pSlot - aData));
7815 pCellptr += 2;
7816 i++;
7817 if( i>=iEnd ) break;
7818 if( pCArray->ixNx[k]<=i ){
7819 k++;
7820 pEnd = pCArray->apEnd[k];
7821 }
7822 }
7823 *ppData = pData;
7824 return 0;
7825}
7826
7827/*
7828** The pCArray object contains pointers to b-tree cells and their sizes.
7829**
7830** This function adds the space associated with each cell in the array
7831** that is currently stored within the body of pPg to the pPg free-list.
7832** The cell-pointers and other fields of the page are not updated.
7833**
7834** This function returns the total number of cells added to the free-list.
7835*/
7836static int pageFreeArray(
7837 MemPage *pPg, /* Page to edit */
7838 int iFirst, /* First cell to delete */
7839 int nCell, /* Cells to delete */
7840 CellArray *pCArray /* Array of cells */
7841){
7842 u8 * const aData = pPg->aData;
7843 u8 * const pEnd = &aData[pPg->pBt->usableSize];
7844 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
7845 int nRet = 0;
7846 int i, j;
7847 int iEnd = iFirst + nCell;
7848 int nFree = 0;
7849 int aOfst[10];
7850 int aAfter[10];
7851
7852 for(i=iFirst; i<iEnd; i++){
7853 u8 *pCell = pCArray->apCell[i];
7854 if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
7855 int sz;
7856 int iAfter;
7857 int iOfst;
7858 /* No need to use cachedCellSize() here. The sizes of all cells that
7859 ** are to be freed have already been computing while deciding which
7860 ** cells need freeing */
7861 sz = pCArray->szCell[i]; assert( sz>0 );
7862 iOfst = (u16)(pCell - aData);
7863 iAfter = iOfst+sz;
7864 for(j=0; j<nFree; j++){
7865 if( aOfst[j]==iAfter ){
7866 aOfst[j] = iOfst;
7867 break;
7868 }else if( aAfter[j]==iOfst ){
7869 aAfter[j] = iAfter;
7870 break;
7871 }
7872 }
7873 if( j>=nFree ){
7874 if( nFree>=(int)(sizeof(aOfst)/sizeof(aOfst[0])) ){
7875 for(j=0; j<nFree; j++){
7876 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7877 }
7878 nFree = 0;
7879 }
7880 aOfst[nFree] = iOfst;
7881 aAfter[nFree] = iAfter;
7882 if( &aData[iAfter]>pEnd ) return 0;
7883 nFree++;
7884 }
7885 nRet++;
7886 }
7887 }
7888 for(j=0; j<nFree; j++){
7889 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
7890 }
7891 return nRet;
7892}
7893
7894/*
7895** pCArray contains pointers to and sizes of all cells in the page being
7896** balanced. The current page, pPg, has pPg->nCell cells starting with
7897** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
7898** starting at apCell[iNew].
7899**
7900** This routine makes the necessary adjustments to pPg so that it contains
7901** the correct cells after being balanced.
7902**
7903** The pPg->nFree field is invalid when this function returns. It is the
7904** responsibility of the caller to set it correctly.
7905*/
7906static int editPage(
7907 MemPage *pPg, /* Edit this page */
7908 int iOld, /* Index of first cell currently on page */
7909 int iNew, /* Index of new first cell on page */
7910 int nNew, /* Final number of cells on page */
7911 CellArray *pCArray /* Array of cells and sizes */
7912){
7913 u8 * const aData = pPg->aData;
7914 const int hdr = pPg->hdrOffset;
7915 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
7916 int nCell = pPg->nCell; /* Cells stored on pPg */
7917 u8 *pData;
7918 u8 *pCellptr;
7919 int i;
7920 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
7921 int iNewEnd = iNew + nNew;
7922
7923#ifdef SQLITE_DEBUG
7924 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
7925 memcpy(pTmp, aData, pPg->pBt->usableSize);
7926#endif
7927
7928 /* Remove cells from the start and end of the page */
7929 assert( nCell>=0 );
7930 if( iOld<iNew ){
7931 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
7932 if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
7933 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
7934 nCell -= nShift;
7935 }
7936 if( iNewEnd < iOldEnd ){
7937 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
7938 assert( nCell>=nTail );
7939 nCell -= nTail;
7940 }
7941
7942 pData = &aData[get2byte(&aData[hdr+5])];
7943 if( pData<pBegin ) goto editpage_fail;
7944 if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;
7945
7946 /* Add cells to the start of the page */
7947 if( iNew<iOld ){
7948 int nAdd = MIN(nNew,iOld-iNew);
7949 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
7950 assert( nAdd>=0 );
7951 pCellptr = pPg->aCellIdx;
7952 memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
7953 if( pageInsertArray(
7954 pPg, pBegin, &pData, pCellptr,
7955 iNew, nAdd, pCArray
7956 ) ) goto editpage_fail;
7957 nCell += nAdd;
7958 }
7959
7960 /* Add any overflow cells */
7961 for(i=0; i<pPg->nOverflow; i++){
7962 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
7963 if( iCell>=0 && iCell<nNew ){
7964 pCellptr = &pPg->aCellIdx[iCell * 2];
7965 if( nCell>iCell ){
7966 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
7967 }
7968 nCell++;
7969 cachedCellSize(pCArray, iCell+iNew);
7970 if( pageInsertArray(
7971 pPg, pBegin, &pData, pCellptr,
7972 iCell+iNew, 1, pCArray
7973 ) ) goto editpage_fail;
7974 }
7975 }
7976
7977 /* Append cells to the end of the page */
7978 assert( nCell>=0 );
7979 pCellptr = &pPg->aCellIdx[nCell*2];
7980 if( pageInsertArray(
7981 pPg, pBegin, &pData, pCellptr,
7982 iNew+nCell, nNew-nCell, pCArray
7983 )
7984 ){
7985 goto editpage_fail;
7986 }
7987
7988 assert( nNew < 10922 );
7989 pPg->nCell = (u16)nNew;
7990 pPg->nOverflow = 0;
7991
7992 put2byte(&aData[hdr+3], pPg->nCell);
7993 put2byte(&aData[hdr+5], pData - aData);
7994
7995#ifdef SQLITE_DEBUG
7996 for(i=0; i<nNew && !CORRUPT_DB; i++){
7997 u8 *pCell = pCArray->apCell[i+iNew];
7998 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
7999 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
8000 pCell = &pTmp[pCell - aData];
8001 }
8002 assert( 0==memcmp(pCell, &aData[iOff],
8003 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
8004 }
8005#endif
8006
8007 return SQLITE_OK;
8008 editpage_fail:
8009 /* Unable to edit this page. Rebuild it from scratch instead. */
8010 if( nNew<1 ) return SQLITE_CORRUPT_BKPT;
8011 populateCellCache(pCArray, iNew, nNew);
8012 return rebuildPage(pCArray, iNew, nNew, pPg);
8013}
8014
8015
8016#ifndef SQLITE_OMIT_QUICKBALANCE
8017/*
8018** This version of balance() handles the common special case where
8019** a new entry is being inserted on the extreme right-end of the
8020** tree, in other words, when the new entry will become the largest
8021** entry in the tree.
8022**
8023** Instead of trying to balance the 3 right-most leaf pages, just add
8024** a new page to the right-hand side and put the one new entry in
8025** that page. This leaves the right side of the tree somewhat
8026** unbalanced. But odds are that we will be inserting new entries
8027** at the end soon afterwards so the nearly empty page will quickly
8028** fill up. On average.
8029**
8030** pPage is the leaf page which is the right-most page in the tree.
8031** pParent is its parent. pPage must have a single overflow entry
8032** which is also the right-most entry on the page.
8033**
8034** The pSpace buffer is used to store a temporary copy of the divider
8035** cell that will be inserted into pParent. Such a cell consists of a 4
8036** byte page number followed by a variable length integer. In other
8037** words, at most 13 bytes. Hence the pSpace buffer must be at
8038** least 13 bytes in size.
8039*/
8040static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
8041 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
8042 MemPage *pNew; /* Newly allocated page */
8043 int rc; /* Return Code */
8044 Pgno pgnoNew; /* Page number of pNew */
8045
8046 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
8047 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8048 assert( pPage->nOverflow==1 );
8049
8050 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
8051 assert( pPage->nFree>=0 );
8052 assert( pParent->nFree>=0 );
8053
8054 /* Allocate a new page. This page will become the right-sibling of
8055 ** pPage. Make the parent page writable, so that the new divider cell
8056 ** may be inserted. If both these operations are successful, proceed.
8057 */
8058 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
8059
8060 if( rc==SQLITE_OK ){
8061
8062 u8 *pOut = &pSpace[4];
8063 u8 *pCell = pPage->apOvfl[0];
8064 u16 szCell = pPage->xCellSize(pPage, pCell);
8065 u8 *pStop;
8066 CellArray b;
8067
8068 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
8069 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
8070 zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
8071 b.nCell = 1;
8072 b.pRef = pPage;
8073 b.apCell = &pCell;
8074 b.szCell = &szCell;
8075 b.apEnd[0] = pPage->aDataEnd;
8076 b.ixNx[0] = 2;
8077 b.ixNx[NB*2-1] = 0x7fffffff;
8078 rc = rebuildPage(&b, 0, 1, pNew);
8079 if( NEVER(rc) ){
8080 releasePage(pNew);
8081 return rc;
8082 }
8083 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
8084
8085 /* If this is an auto-vacuum database, update the pointer map
8086 ** with entries for the new page, and any pointer from the
8087 ** cell on the page to an overflow page. If either of these
8088 ** operations fails, the return code is set, but the contents
8089 ** of the parent page are still manipulated by the code below.
8090 ** That is Ok, at this point the parent page is guaranteed to
8091 ** be marked as dirty. Returning an error code will cause a
8092 ** rollback, undoing any changes made to the parent page.
8093 */
8094 if( ISAUTOVACUUM(pBt) ){
8095 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
8096 if( szCell>pNew->minLocal ){
8097 ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
8098 }
8099 }
8100
8101 /* Create a divider cell to insert into pParent. The divider cell
8102 ** consists of a 4-byte page number (the page number of pPage) and
8103 ** a variable length key value (which must be the same value as the
8104 ** largest key on pPage).
8105 **
8106 ** To find the largest key value on pPage, first find the right-most
8107 ** cell on pPage. The first two fields of this cell are the
8108 ** record-length (a variable length integer at most 32-bits in size)
8109 ** and the key value (a variable length integer, may have any value).
8110 ** The first of the while(...) loops below skips over the record-length
8111 ** field. The second while(...) loop copies the key value from the
8112 ** cell on pPage into the pSpace buffer.
8113 */
8114 pCell = findCell(pPage, pPage->nCell-1);
8115 pStop = &pCell[9];
8116 while( (*(pCell++)&0x80) && pCell<pStop );
8117 pStop = &pCell[9];
8118 while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
8119
8120 /* Insert the new divider cell into pParent. */
8121 if( rc==SQLITE_OK ){
8122 rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
8123 0, pPage->pgno);
8124 }
8125
8126 /* Set the right-child pointer of pParent to point to the new page. */
8127 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
8128
8129 /* Release the reference to the new page. */
8130 releasePage(pNew);
8131 }
8132
8133 return rc;
8134}
8135#endif /* SQLITE_OMIT_QUICKBALANCE */
8136
8137#if 0
8138/*
8139** This function does not contribute anything to the operation of SQLite.
8140** it is sometimes activated temporarily while debugging code responsible
8141** for setting pointer-map entries.
8142*/
8143static int ptrmapCheckPages(MemPage **apPage, int nPage){
8144 int i, j;
8145 for(i=0; i<nPage; i++){
8146 Pgno n;
8147 u8 e;
8148 MemPage *pPage = apPage[i];
8149 BtShared *pBt = pPage->pBt;
8150 assert( pPage->isInit );
8151
8152 for(j=0; j<pPage->nCell; j++){
8153 CellInfo info;
8154 u8 *z;
8155
8156 z = findCell(pPage, j);
8157 pPage->xParseCell(pPage, z, &info);
8158 if( info.nLocal<info.nPayload ){
8159 Pgno ovfl = get4byte(&z[info.nSize-4]);
8160 ptrmapGet(pBt, ovfl, &e, &n);
8161 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
8162 }
8163 if( !pPage->leaf ){
8164 Pgno child = get4byte(z);
8165 ptrmapGet(pBt, child, &e, &n);
8166 assert( n==pPage->pgno && e==PTRMAP_BTREE );
8167 }
8168 }
8169 if( !pPage->leaf ){
8170 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
8171 ptrmapGet(pBt, child, &e, &n);
8172 assert( n==pPage->pgno && e==PTRMAP_BTREE );
8173 }
8174 }
8175 return 1;
8176}
8177#endif
8178
8179/*
8180** This function is used to copy the contents of the b-tree node stored
8181** on page pFrom to page pTo. If page pFrom was not a leaf page, then
8182** the pointer-map entries for each child page are updated so that the
8183** parent page stored in the pointer map is page pTo. If pFrom contained
8184** any cells with overflow page pointers, then the corresponding pointer
8185** map entries are also updated so that the parent page is page pTo.
8186**
8187** If pFrom is currently carrying any overflow cells (entries in the
8188** MemPage.apOvfl[] array), they are not copied to pTo.
8189**
8190** Before returning, page pTo is reinitialized using btreeInitPage().
8191**
8192** The performance of this function is not critical. It is only used by
8193** the balance_shallower() and balance_deeper() procedures, neither of
8194** which are called often under normal circumstances.
8195*/
8196static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
8197 if( (*pRC)==SQLITE_OK ){
8198 BtShared * const pBt = pFrom->pBt;
8199 u8 * const aFrom = pFrom->aData;
8200 u8 * const aTo = pTo->aData;
8201 int const iFromHdr = pFrom->hdrOffset;
8202 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
8203 int rc;
8204 int iData;
8205
8206
8207 assert( pFrom->isInit );
8208 assert( pFrom->nFree>=iToHdr );
8209 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
8210
8211 /* Copy the b-tree node content from page pFrom to page pTo. */
8212 iData = get2byte(&aFrom[iFromHdr+5]);
8213 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
8214 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
8215
8216 /* Reinitialize page pTo so that the contents of the MemPage structure
8217 ** match the new data. The initialization of pTo can actually fail under
8218 ** fairly obscure circumstances, even though it is a copy of initialized
8219 ** page pFrom.
8220 */
8221 pTo->isInit = 0;
8222 rc = btreeInitPage(pTo);
8223 if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
8224 if( rc!=SQLITE_OK ){
8225 *pRC = rc;
8226 return;
8227 }
8228
8229 /* If this is an auto-vacuum database, update the pointer-map entries
8230 ** for any b-tree or overflow pages that pTo now contains the pointers to.
8231 */
8232 if( ISAUTOVACUUM(pBt) ){
8233 *pRC = setChildPtrmaps(pTo);
8234 }
8235 }
8236}
8237
8238/*
8239** This routine redistributes cells on the iParentIdx'th child of pParent
8240** (hereafter "the page") and up to 2 siblings so that all pages have about the
8241** same amount of free space. Usually a single sibling on either side of the
8242** page are used in the balancing, though both siblings might come from one
8243** side if the page is the first or last child of its parent. If the page
8244** has fewer than 2 siblings (something which can only happen if the page
8245** is a root page or a child of a root page) then all available siblings
8246** participate in the balancing.
8247**
8248** The number of siblings of the page might be increased or decreased by
8249** one or two in an effort to keep pages nearly full but not over full.
8250**
8251** Note that when this routine is called, some of the cells on the page
8252** might not actually be stored in MemPage.aData[]. This can happen
8253** if the page is overfull. This routine ensures that all cells allocated
8254** to the page and its siblings fit into MemPage.aData[] before returning.
8255**
8256** In the course of balancing the page and its siblings, cells may be
8257** inserted into or removed from the parent page (pParent). Doing so
8258** may cause the parent page to become overfull or underfull. If this
8259** happens, it is the responsibility of the caller to invoke the correct
8260** balancing routine to fix this problem (see the balance() routine).
8261**
8262** If this routine fails for any reason, it might leave the database
8263** in a corrupted state. So if this routine fails, the database should
8264** be rolled back.
8265**
8266** The third argument to this function, aOvflSpace, is a pointer to a
8267** buffer big enough to hold one page. If while inserting cells into the parent
8268** page (pParent) the parent page becomes overfull, this buffer is
8269** used to store the parent's overflow cells. Because this function inserts
8270** a maximum of four divider cells into the parent page, and the maximum
8271** size of a cell stored within an internal node is always less than 1/4
8272** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
8273** enough for all overflow cells.
8274**
8275** If aOvflSpace is set to a null pointer, this function returns
8276** SQLITE_NOMEM.
8277*/
8278static int balance_nonroot(
8279 MemPage *pParent, /* Parent page of siblings being balanced */
8280 int iParentIdx, /* Index of "the page" in pParent */
8281 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
8282 int isRoot, /* True if pParent is a root-page */
8283 int bBulk /* True if this call is part of a bulk load */
8284){
8285 BtShared *pBt; /* The whole database */
8286 int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
8287 int nNew = 0; /* Number of pages in apNew[] */
8288 int nOld; /* Number of pages in apOld[] */
8289 int i, j, k; /* Loop counters */
8290 int nxDiv; /* Next divider slot in pParent->aCell[] */
8291 int rc = SQLITE_OK; /* The return code */
8292 u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
8293 int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
8294 int usableSpace; /* Bytes in pPage beyond the header */
8295 int pageFlags; /* Value of pPage->aData[0] */
8296 int iSpace1 = 0; /* First unused byte of aSpace1[] */
8297 int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
8298 u64 szScratch; /* Size of scratch memory requested */
8299 MemPage *apOld[NB]; /* pPage and up to two siblings */
8300 MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
8301 u8 *pRight; /* Location in parent of right-sibling pointer */
8302 u8 *apDiv[NB-1]; /* Divider cells in pParent */
8303 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
8304 int cntOld[NB+2]; /* Old index in b.apCell[] */
8305 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
8306 u8 *aSpace1; /* Space for copies of dividers cells */
8307 Pgno pgno; /* Temp var to store a page number in */
8308 u8 abDone[NB+2]; /* True after i'th new page is populated */
8309 Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
8310 CellArray b; /* Parsed information on cells being balanced */
8311
8312 memset(abDone, 0, sizeof(abDone));
8313 assert( sizeof(b) - sizeof(b.ixNx) == offsetof(CellArray,ixNx) );
8314 memset(&b, 0, sizeof(b)-sizeof(b.ixNx[0]));
8315 b.ixNx[NB*2-1] = 0x7fffffff;
8316 pBt = pParent->pBt;
8317 assert( sqlite3_mutex_held(pBt->mutex) );
8318 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8319
8320 /* At this point pParent may have at most one overflow cell. And if
8321 ** this overflow cell is present, it must be the cell with
8322 ** index iParentIdx. This scenario comes about when this function
8323 ** is called (indirectly) from sqlite3BtreeDelete().
8324 */
8325 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
8326 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
8327
8328 if( !aOvflSpace ){
8329 return SQLITE_NOMEM_BKPT;
8330 }
8331 assert( pParent->nFree>=0 );
8332
8333 /* Find the sibling pages to balance. Also locate the cells in pParent
8334 ** that divide the siblings. An attempt is made to find NN siblings on
8335 ** either side of pPage. More siblings are taken from one side, however,
8336 ** if there are fewer than NN siblings on the other side. If pParent
8337 ** has NB or fewer children then all children of pParent are taken.
8338 **
8339 ** This loop also drops the divider cells from the parent page. This
8340 ** way, the remainder of the function does not have to deal with any
8341 ** overflow cells in the parent page, since if any existed they will
8342 ** have already been removed.
8343 */
8344 i = pParent->nOverflow + pParent->nCell;
8345 if( i<2 ){
8346 nxDiv = 0;
8347 }else{
8348 assert( bBulk==0 || bBulk==1 );
8349 if( iParentIdx==0 ){
8350 nxDiv = 0;
8351 }else if( iParentIdx==i ){
8352 nxDiv = i-2+bBulk;
8353 }else{
8354 nxDiv = iParentIdx-1;
8355 }
8356 i = 2-bBulk;
8357 }
8358 nOld = i+1;
8359 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
8360 pRight = &pParent->aData[pParent->hdrOffset+8];
8361 }else{
8362 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
8363 }
8364 pgno = get4byte(pRight);
8365 while( 1 ){
8366 if( rc==SQLITE_OK ){
8367 rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
8368 }
8369 if( rc ){
8370 memset(apOld, 0, (i+1)*sizeof(MemPage*));
8371 goto balance_cleanup;
8372 }
8373 if( apOld[i]->nFree<0 ){
8374 rc = btreeComputeFreeSpace(apOld[i]);
8375 if( rc ){
8376 memset(apOld, 0, (i)*sizeof(MemPage*));
8377 goto balance_cleanup;
8378 }
8379 }
8380 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
8381 if( (i--)==0 ) break;
8382
8383 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
8384 apDiv[i] = pParent->apOvfl[0];
8385 pgno = get4byte(apDiv[i]);
8386 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8387 pParent->nOverflow = 0;
8388 }else{
8389 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
8390 pgno = get4byte(apDiv[i]);
8391 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
8392
8393 /* Drop the cell from the parent page. apDiv[i] still points to
8394 ** the cell within the parent, even though it has been dropped.
8395 ** This is safe because dropping a cell only overwrites the first
8396 ** four bytes of it, and this function does not need the first
8397 ** four bytes of the divider cell. So the pointer is safe to use
8398 ** later on.
8399 **
8400 ** But not if we are in secure-delete mode. In secure-delete mode,
8401 ** the dropCell() routine will overwrite the entire cell with zeroes.
8402 ** In this case, temporarily copy the cell into the aOvflSpace[]
8403 ** buffer. It will be copied out again as soon as the aSpace[] buffer
8404 ** is allocated. */
8405 if( pBt->btsFlags & BTS_FAST_SECURE ){
8406 int iOff;
8407
8408 /* If the following if() condition is not true, the db is corrupted.
8409 ** The call to dropCell() below will detect this. */
8410 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
8411 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
8412 memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
8413 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
8414 }
8415 }
8416 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
8417 }
8418 }
8419
8420 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
8421 ** alignment */
8422 nMaxCells = (nMaxCells + 3)&~3;
8423
8424 /*
8425 ** Allocate space for memory structures
8426 */
8427 szScratch =
8428 nMaxCells*sizeof(u8*) /* b.apCell */
8429 + nMaxCells*sizeof(u16) /* b.szCell */
8430 + pBt->pageSize; /* aSpace1 */
8431
8432 assert( szScratch<=7*(int)pBt->pageSize );
8433 b.apCell = sqlite3StackAllocRaw(0, szScratch );
8434 if( b.apCell==0 ){
8435 rc = SQLITE_NOMEM_BKPT;
8436 goto balance_cleanup;
8437 }
8438 b.szCell = (u16*)&b.apCell[nMaxCells];
8439 aSpace1 = (u8*)&b.szCell[nMaxCells];
8440 assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
8441
8442 /*
8443 ** Load pointers to all cells on sibling pages and the divider cells
8444 ** into the local b.apCell[] array. Make copies of the divider cells
8445 ** into space obtained from aSpace1[]. The divider cells have already
8446 ** been removed from pParent.
8447 **
8448 ** If the siblings are on leaf pages, then the child pointers of the
8449 ** divider cells are stripped from the cells before they are copied
8450 ** into aSpace1[]. In this way, all cells in b.apCell[] are without
8451 ** child pointers. If siblings are not leaves, then all cell in
8452 ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
8453 ** are alike.
8454 **
8455 ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
8456 ** leafData: 1 if pPage holds key+data and pParent holds only keys.
8457 */
8458 b.pRef = apOld[0];
8459 leafCorrection = b.pRef->leaf*4;
8460 leafData = b.pRef->intKeyLeaf;
8461 for(i=0; i<nOld; i++){
8462 MemPage *pOld = apOld[i];
8463 int limit = pOld->nCell;
8464 u8 *aData = pOld->aData;
8465 u16 maskPage = pOld->maskPage;
8466 u8 *piCell = aData + pOld->cellOffset;
8467 u8 *piEnd;
8468 u8 **ppCell;
8469 VVA_ONLY( int nCellAtStart = b.nCell; )
8470
8471 /* Verify that all sibling pages are of the same "type" (table-leaf,
8472 ** table-interior, index-leaf, or index-interior).
8473 */
8474 if( pOld->aData[0]!=apOld[0]->aData[0] ){
8475 rc = SQLITE_CORRUPT_PAGE(pOld);
8476 goto balance_cleanup;
8477 }
8478
8479 /* Load b.apCell[] with pointers to all cells in pOld. If pOld
8480 ** contains overflow cells, include them in the b.apCell[] array
8481 ** in the correct spot.
8482 **
8483 ** Note that when there are multiple overflow cells, it is always the
8484 ** case that they are sequential and adjacent. This invariant arises
8485 ** because multiple overflows can only occurs when inserting divider
8486 ** cells into a parent on a prior balance, and divider cells are always
8487 ** adjacent and are inserted in order. There is an assert() tagged
8488 ** with "NOTE 1" in the overflow cell insertion loop to prove this
8489 ** invariant.
8490 **
8491 ** This must be done in advance. Once the balance starts, the cell
8492 ** offset section of the btree page will be overwritten and we will no
8493 ** long be able to find the cells if a pointer to each cell is not saved
8494 ** first.
8495 */
8496 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
8497 if( pOld->nOverflow>0 ){
8498 if( NEVER(limit<pOld->aiOvfl[0]) ){
8499 rc = SQLITE_CORRUPT_PAGE(pOld);
8500 goto balance_cleanup;
8501 }
8502 limit = pOld->aiOvfl[0];
8503 for(j=0; j<limit; j++){
8504 b.apCell[b.nCell+j] = aData + (maskPage & get2byteAligned(piCell));
8505 piCell += 2;
8506 }
8507 b.nCell += limit;
8508 for(k=0; k<pOld->nOverflow; k++){
8509 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
8510 b.apCell[b.nCell] = pOld->apOvfl[k];
8511 b.nCell++;
8512 }
8513 }
8514 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
8515 /* Collect cell pointers before updating the cell count. */
8516 ppCell = &b.apCell[b.nCell];
8517 while( piCell<piEnd ){
8518 assert( ppCell<&b.apCell[nMaxCells] );
8519 *ppCell++ = aData + (maskPage & get2byteAligned(piCell));
8520 piCell += 2;
8521 }
8522 b.nCell = (int)(ppCell - b.apCell);
8523 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
8524
8525 cntOld[i] = b.nCell;
8526 if( i<nOld-1 && !leafData){
8527 u16 sz = (u16)szNew[i];
8528 u8 *pTemp;
8529 assert( b.nCell<nMaxCells );
8530 b.szCell[b.nCell] = sz;
8531 pTemp = &aSpace1[iSpace1];
8532 iSpace1 += sz;
8533 assert( sz<=pBt->maxLocal+23 );
8534 assert( iSpace1 <= (int)pBt->pageSize );
8535 memcpy(pTemp, apDiv[i], sz);
8536 b.apCell[b.nCell] = pTemp+leafCorrection;
8537 assert( leafCorrection==0 || leafCorrection==4 );
8538 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
8539 if( !pOld->leaf ){
8540 assert( leafCorrection==0 );
8541 assert( pOld->hdrOffset==0 || CORRUPT_DB );
8542 /* The right pointer of the child page pOld becomes the left
8543 ** pointer of the divider cell */
8544 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
8545 }else{
8546 assert( leafCorrection==4 );
8547 while( b.szCell[b.nCell]<4 ){
8548 /* Do not allow any cells smaller than 4 bytes. If a smaller cell
8549 ** does exist, pad it with 0x00 bytes. */
8550 assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
8551 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
8552 aSpace1[iSpace1++] = 0x00;
8553 b.szCell[b.nCell]++;
8554 }
8555 }
8556 b.nCell++;
8557 }
8558 }
8559
8560 /*
8561 ** Figure out the number of pages needed to hold all b.nCell cells.
8562 ** Store this number in "k". Also compute szNew[] which is the total
8563 ** size of all cells on the i-th page and cntNew[] which is the index
8564 ** in b.apCell[] of the cell that divides page i from page i+1.
8565 ** cntNew[k] should equal b.nCell.
8566 **
8567 ** Values computed by this block:
8568 **
8569 ** k: The total number of sibling pages
8570 ** szNew[i]: Spaced used on the i-th sibling page.
8571 ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
8572 ** the right of the i-th sibling page.
8573 ** usableSpace: Number of bytes of space available on each sibling.
8574 **
8575 */
8576 usableSpace = pBt->usableSize - 12 + leafCorrection;
8577 for(i=k=0; i<nOld; i++, k++){
8578 MemPage *p = apOld[i];
8579 b.apEnd[k] = p->aDataEnd;
8580 b.ixNx[k] = cntOld[i];
8581 if( k && b.ixNx[k]==b.ixNx[k-1] ){
8582 k--; /* Omit b.ixNx[] entry for child pages with no cells */
8583 }
8584 if( !leafData ){
8585 k++;
8586 b.apEnd[k] = pParent->aDataEnd;
8587 b.ixNx[k] = cntOld[i]+1;
8588 }
8589 assert( p->nFree>=0 );
8590 szNew[i] = usableSpace - p->nFree;
8591 for(j=0; j<p->nOverflow; j++){
8592 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
8593 }
8594 cntNew[i] = cntOld[i];
8595 }
8596 k = nOld;
8597 for(i=0; i<k; i++){
8598 int sz;
8599 while( szNew[i]>usableSpace ){
8600 if( i+1>=k ){
8601 k = i+2;
8602 if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
8603 szNew[k-1] = 0;
8604 cntNew[k-1] = b.nCell;
8605 }
8606 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
8607 szNew[i] -= sz;
8608 if( !leafData ){
8609 if( cntNew[i]<b.nCell ){
8610 sz = 2 + cachedCellSize(&b, cntNew[i]);
8611 }else{
8612 sz = 0;
8613 }
8614 }
8615 szNew[i+1] += sz;
8616 cntNew[i]--;
8617 }
8618 while( cntNew[i]<b.nCell ){
8619 sz = 2 + cachedCellSize(&b, cntNew[i]);
8620 if( szNew[i]+sz>usableSpace ) break;
8621 szNew[i] += sz;
8622 cntNew[i]++;
8623 if( !leafData ){
8624 if( cntNew[i]<b.nCell ){
8625 sz = 2 + cachedCellSize(&b, cntNew[i]);
8626 }else{
8627 sz = 0;
8628 }
8629 }
8630 szNew[i+1] -= sz;
8631 }
8632 if( cntNew[i]>=b.nCell ){
8633 k = i+1;
8634 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
8635 rc = SQLITE_CORRUPT_BKPT;
8636 goto balance_cleanup;
8637 }
8638 }
8639
8640 /*
8641 ** The packing computed by the previous block is biased toward the siblings
8642 ** on the left side (siblings with smaller keys). The left siblings are
8643 ** always nearly full, while the right-most sibling might be nearly empty.
8644 ** The next block of code attempts to adjust the packing of siblings to
8645 ** get a better balance.
8646 **
8647 ** This adjustment is more than an optimization. The packing above might
8648 ** be so out of balance as to be illegal. For example, the right-most
8649 ** sibling might be completely empty. This adjustment is not optional.
8650 */
8651 for(i=k-1; i>0; i--){
8652 int szRight = szNew[i]; /* Size of sibling on the right */
8653 int szLeft = szNew[i-1]; /* Size of sibling on the left */
8654 int r; /* Index of right-most cell in left sibling */
8655 int d; /* Index of first cell to the left of right sibling */
8656
8657 r = cntNew[i-1] - 1;
8658 d = r + 1 - leafData;
8659 (void)cachedCellSize(&b, d);
8660 do{
8661 int szR, szD;
8662 assert( d<nMaxCells );
8663 assert( r<nMaxCells );
8664 szR = cachedCellSize(&b, r);
8665 szD = b.szCell[d];
8666 if( szRight!=0
8667 && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){
8668 break;
8669 }
8670 szRight += szD + 2;
8671 szLeft -= szR + 2;
8672 cntNew[i-1] = r;
8673 r--;
8674 d--;
8675 }while( r>=0 );
8676 szNew[i] = szRight;
8677 szNew[i-1] = szLeft;
8678 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
8679 rc = SQLITE_CORRUPT_BKPT;
8680 goto balance_cleanup;
8681 }
8682 }
8683
8684 /* Sanity check: For a non-corrupt database file one of the following
8685 ** must be true:
8686 ** (1) We found one or more cells (cntNew[0])>0), or
8687 ** (2) pPage is a virtual root page. A virtual root page is when
8688 ** the real root page is page 1 and we are the only child of
8689 ** that page.
8690 */
8691 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
8692 TRACE(("BALANCE: old: %u(nc=%u) %u(nc=%u) %u(nc=%u)\n",
8693 apOld[0]->pgno, apOld[0]->nCell,
8694 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
8695 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
8696 ));
8697
8698 /*
8699 ** Allocate k new pages. Reuse old pages where possible.
8700 */
8701 pageFlags = apOld[0]->aData[0];
8702 for(i=0; i<k; i++){
8703 MemPage *pNew;
8704 if( i<nOld ){
8705 pNew = apNew[i] = apOld[i];
8706 apOld[i] = 0;
8707 rc = sqlite3PagerWrite(pNew->pDbPage);
8708 nNew++;
8709 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
8710 && rc==SQLITE_OK
8711 ){
8712 rc = SQLITE_CORRUPT_BKPT;
8713 }
8714 if( rc ) goto balance_cleanup;
8715 }else{
8716 assert( i>0 );
8717 rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
8718 if( rc ) goto balance_cleanup;
8719 zeroPage(pNew, pageFlags);
8720 apNew[i] = pNew;
8721 nNew++;
8722 cntOld[i] = b.nCell;
8723
8724 /* Set the pointer-map entry for the new sibling page. */
8725 if( ISAUTOVACUUM(pBt) ){
8726 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
8727 if( rc!=SQLITE_OK ){
8728 goto balance_cleanup;
8729 }
8730 }
8731 }
8732 }
8733
8734 /*
8735 ** Reassign page numbers so that the new pages are in ascending order.
8736 ** This helps to keep entries in the disk file in order so that a scan
8737 ** of the table is closer to a linear scan through the file. That in turn
8738 ** helps the operating system to deliver pages from the disk more rapidly.
8739 **
8740 ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
8741 ** (5), that is not a performance concern.
8742 **
8743 ** When NB==3, this one optimization makes the database about 25% faster
8744 ** for large insertions and deletions.
8745 */
8746 for(i=0; i<nNew; i++){
8747 aPgno[i] = apNew[i]->pgno;
8748 assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
8749 assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
8750 }
8751 for(i=0; i<nNew-1; i++){
8752 int iB = i;
8753 for(j=i+1; j<nNew; j++){
8754 if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
8755 }
8756
8757 /* If apNew[i] has a page number that is bigger than any of the
8758 ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
8759 ** entry that has the smallest page number (which we know to be
8760 ** entry apNew[iB]).
8761 */
8762 if( iB!=i ){
8763 Pgno pgnoA = apNew[i]->pgno;
8764 Pgno pgnoB = apNew[iB]->pgno;
8765 Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
8766 u16 fgA = apNew[i]->pDbPage->flags;
8767 u16 fgB = apNew[iB]->pDbPage->flags;
8768 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
8769 sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
8770 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
8771 apNew[i]->pgno = pgnoB;
8772 apNew[iB]->pgno = pgnoA;
8773 }
8774 }
8775
8776 TRACE(("BALANCE: new: %u(%u nc=%u) %u(%u nc=%u) %u(%u nc=%u) "
8777 "%u(%u nc=%u) %u(%u nc=%u)\n",
8778 apNew[0]->pgno, szNew[0], cntNew[0],
8779 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
8780 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
8781 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
8782 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
8783 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
8784 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
8785 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
8786 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
8787 ));
8788
8789 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8790 assert( nNew>=1 && nNew<=ArraySize(apNew) );
8791 assert( apNew[nNew-1]!=0 );
8792 put4byte(pRight, apNew[nNew-1]->pgno);
8793
8794 /* If the sibling pages are not leaves, ensure that the right-child pointer
8795 ** of the right-most new sibling page is set to the value that was
8796 ** originally in the same field of the right-most old sibling page. */
8797 if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
8798 MemPage *pOld;
8799 if( nNew>nOld ){
8800 pOld = apNew[nOld-1];
8801 }else{
8802 pOld = apOld[nOld-1];
8803 }
8804 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
8805 }
8806
8807 /* Make any required updates to pointer map entries associated with
8808 ** cells stored on sibling pages following the balance operation. Pointer
8809 ** map entries associated with divider cells are set by the insertCell()
8810 ** routine. The associated pointer map entries are:
8811 **
8812 ** a) if the cell contains a reference to an overflow chain, the
8813 ** entry associated with the first page in the overflow chain, and
8814 **
8815 ** b) if the sibling pages are not leaves, the child page associated
8816 ** with the cell.
8817 **
8818 ** If the sibling pages are not leaves, then the pointer map entry
8819 ** associated with the right-child of each sibling may also need to be
8820 ** updated. This happens below, after the sibling pages have been
8821 ** populated, not here.
8822 */
8823 if( ISAUTOVACUUM(pBt) ){
8824 MemPage *pOld;
8825 MemPage *pNew = pOld = apNew[0];
8826 int cntOldNext = pNew->nCell + pNew->nOverflow;
8827 int iNew = 0;
8828 int iOld = 0;
8829
8830 for(i=0; i<b.nCell; i++){
8831 u8 *pCell = b.apCell[i];
8832 while( i==cntOldNext ){
8833 iOld++;
8834 assert( iOld<nNew || iOld<nOld );
8835 assert( iOld>=0 && iOld<NB );
8836 pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
8837 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
8838 }
8839 if( i==cntNew[iNew] ){
8840 pNew = apNew[++iNew];
8841 if( !leafData ) continue;
8842 }
8843
8844 /* Cell pCell is destined for new sibling page pNew. Originally, it
8845 ** was either part of sibling page iOld (possibly an overflow cell),
8846 ** or else the divider cell to the left of sibling page iOld. So,
8847 ** if sibling page iOld had the same page number as pNew, and if
8848 ** pCell really was a part of sibling page iOld (not a divider or
8849 ** overflow cell), we can skip updating the pointer map entries. */
8850 if( iOld>=nNew
8851 || pNew->pgno!=aPgno[iOld]
8852 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
8853 ){
8854 if( !leafCorrection ){
8855 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
8856 }
8857 if( cachedCellSize(&b,i)>pNew->minLocal ){
8858 ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
8859 }
8860 if( rc ) goto balance_cleanup;
8861 }
8862 }
8863 }
8864
8865 /* Insert new divider cells into pParent. */
8866 for(i=0; i<nNew-1; i++){
8867 u8 *pCell;
8868 u8 *pTemp;
8869 int sz;
8870 u8 *pSrcEnd;
8871 MemPage *pNew = apNew[i];
8872 j = cntNew[i];
8873
8874 assert( j<nMaxCells );
8875 assert( b.apCell[j]!=0 );
8876 pCell = b.apCell[j];
8877 sz = b.szCell[j] + leafCorrection;
8878 pTemp = &aOvflSpace[iOvflSpace];
8879 if( !pNew->leaf ){
8880 memcpy(&pNew->aData[8], pCell, 4);
8881 }else if( leafData ){
8882 /* If the tree is a leaf-data tree, and the siblings are leaves,
8883 ** then there is no divider cell in b.apCell[]. Instead, the divider
8884 ** cell consists of the integer key for the right-most cell of
8885 ** the sibling-page assembled above only.
8886 */
8887 CellInfo info;
8888 j--;
8889 pNew->xParseCell(pNew, b.apCell[j], &info);
8890 pCell = pTemp;
8891 sz = 4 + sqlite3PutVarint(&pCell[4], info.nKey);
8892 pTemp = 0;
8893 }else{
8894 pCell -= 4;
8895 /* Obscure case for non-leaf-data trees: If the cell at pCell was
8896 ** previously stored on a leaf node, and its reported size was 4
8897 ** bytes, then it may actually be smaller than this
8898 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
8899 ** any cell). But it is important to pass the correct size to
8900 ** insertCell(), so reparse the cell now.
8901 **
8902 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
8903 ** and WITHOUT ROWID tables with exactly one column which is the
8904 ** primary key.
8905 */
8906 if( b.szCell[j]==4 ){
8907 assert(leafCorrection==4);
8908 sz = pParent->xCellSize(pParent, pCell);
8909 }
8910 }
8911 iOvflSpace += sz;
8912 assert( sz<=pBt->maxLocal+23 );
8913 assert( iOvflSpace <= (int)pBt->pageSize );
8914 assert( b.ixNx[NB*2-1]>j );
8915 for(k=0; b.ixNx[k]<=j; k++){}
8916 pSrcEnd = b.apEnd[k];
8917 if( SQLITE_OVERFLOW(pSrcEnd, pCell, pCell+sz) ){
8918 rc = SQLITE_CORRUPT_BKPT;
8919 goto balance_cleanup;
8920 }
8921 rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
8922 if( rc!=SQLITE_OK ) goto balance_cleanup;
8923 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
8924 }
8925
8926 /* Now update the actual sibling pages. The order in which they are updated
8927 ** is important, as this code needs to avoid disrupting any page from which
8928 ** cells may still to be read. In practice, this means:
8929 **
8930 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
8931 ** then it is not safe to update page apNew[iPg] until after
8932 ** the left-hand sibling apNew[iPg-1] has been updated.
8933 **
8934 ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
8935 ** then it is not safe to update page apNew[iPg] until after
8936 ** the right-hand sibling apNew[iPg+1] has been updated.
8937 **
8938 ** If neither of the above apply, the page is safe to update.
8939 **
8940 ** The iPg value in the following loop starts at nNew-1 goes down
8941 ** to 0, then back up to nNew-1 again, thus making two passes over
8942 ** the pages. On the initial downward pass, only condition (1) above
8943 ** needs to be tested because (2) will always be true from the previous
8944 ** step. On the upward pass, both conditions are always true, so the
8945 ** upwards pass simply processes pages that were missed on the downward
8946 ** pass.
8947 */
8948 for(i=1-nNew; i<nNew; i++){
8949 int iPg = i<0 ? -i : i;
8950 assert( iPg>=0 && iPg<nNew );
8951 assert( iPg>=1 || i>=0 );
8952 assert( iPg<ArraySize(cntOld) );
8953 if( abDone[iPg] ) continue; /* Skip pages already processed */
8954 if( i>=0 /* On the upwards pass, or... */
8955 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
8956 ){
8957 int iNew;
8958 int iOld;
8959 int nNewCell;
8960
8961 /* Verify condition (1): If cells are moving left, update iPg
8962 ** only after iPg-1 has already been updated. */
8963 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
8964
8965 /* Verify condition (2): If cells are moving right, update iPg
8966 ** only after iPg+1 has already been updated. */
8967 assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
8968
8969 if( iPg==0 ){
8970 iNew = iOld = 0;
8971 nNewCell = cntNew[0];
8972 }else{
8973 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
8974 iNew = cntNew[iPg-1] + !leafData;
8975 nNewCell = cntNew[iPg] - iNew;
8976 }
8977
8978 rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
8979 if( rc ) goto balance_cleanup;
8980 abDone[iPg]++;
8981 apNew[iPg]->nFree = usableSpace-szNew[iPg];
8982 assert( apNew[iPg]->nOverflow==0 );
8983 assert( apNew[iPg]->nCell==nNewCell );
8984 }
8985 }
8986
8987 /* All pages have been processed exactly once */
8988 assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
8989
8990 assert( nOld>0 );
8991 assert( nNew>0 );
8992
8993 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
8994 /* The root page of the b-tree now contains no cells. The only sibling
8995 ** page is the right-child of the parent. Copy the contents of the
8996 ** child page into the parent, decreasing the overall height of the
8997 ** b-tree structure by one. This is described as the "balance-shallower"
8998 ** sub-algorithm in some documentation.
8999 **
9000 ** If this is an auto-vacuum database, the call to copyNodeContent()
9001 ** sets all pointer-map entries corresponding to database image pages
9002 ** for which the pointer is stored within the content being copied.
9003 **
9004 ** It is critical that the child page be defragmented before being
9005 ** copied into the parent, because if the parent is page 1 then it will
9006 ** by smaller than the child due to the database header, and so all the
9007 ** free space needs to be up front.
9008 */
9009 assert( nNew==1 || CORRUPT_DB );
9010 rc = defragmentPage(apNew[0], -1);
9011 testcase( rc!=SQLITE_OK );
9012 assert( apNew[0]->nFree ==
9013 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
9014 - apNew[0]->nCell*2)
9015 || rc!=SQLITE_OK
9016 );
9017 copyNodeContent(apNew[0], pParent, &rc);
9018 freePage(apNew[0], &rc);
9019 }else if( ISAUTOVACUUM(pBt) && !leafCorrection ){
9020 /* Fix the pointer map entries associated with the right-child of each
9021 ** sibling page. All other pointer map entries have already been taken
9022 ** care of. */
9023 for(i=0; i<nNew; i++){
9024 u32 key = get4byte(&apNew[i]->aData[8]);
9025 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
9026 }
9027 }
9028
9029 assert( pParent->isInit );
9030 TRACE(("BALANCE: finished: old=%u new=%u cells=%u\n",
9031 nOld, nNew, b.nCell));
9032
9033 /* Free any old pages that were not reused as new pages.
9034 */
9035 for(i=nNew; i<nOld; i++){
9036 freePage(apOld[i], &rc);
9037 }
9038
9039#if 0
9040 if( ISAUTOVACUUM(pBt) && rc==SQLITE_OK && apNew[0]->isInit ){
9041 /* The ptrmapCheckPages() contains assert() statements that verify that
9042 ** all pointer map pages are set correctly. This is helpful while
9043 ** debugging. This is usually disabled because a corrupt database may
9044 ** cause an assert() statement to fail. */
9045 ptrmapCheckPages(apNew, nNew);
9046 ptrmapCheckPages(&pParent, 1);
9047 }
9048#endif
9049
9050 /*
9051 ** Cleanup before returning.
9052 */
9053balance_cleanup:
9054 sqlite3StackFree(0, b.apCell);
9055 for(i=0; i<nOld; i++){
9056 releasePage(apOld[i]);
9057 }
9058 for(i=0; i<nNew; i++){
9059 releasePage(apNew[i]);
9060 }
9061
9062 return rc;
9063}
9064
9065
9066/*
9067** This function is called when the root page of a b-tree structure is
9068** overfull (has one or more overflow pages).
9069**
9070** A new child page is allocated and the contents of the current root
9071** page, including overflow cells, are copied into the child. The root
9072** page is then overwritten to make it an empty page with the right-child
9073** pointer pointing to the new page.
9074**
9075** Before returning, all pointer-map entries corresponding to pages
9076** that the new child-page now contains pointers to are updated. The
9077** entry corresponding to the new right-child pointer of the root
9078** page is also updated.
9079**
9080** If successful, *ppChild is set to contain a reference to the child
9081** page and SQLITE_OK is returned. In this case the caller is required
9082** to call releasePage() on *ppChild exactly once. If an error occurs,
9083** an error code is returned and *ppChild is set to 0.
9084*/
9085static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
9086 int rc; /* Return value from subprocedures */
9087 MemPage *pChild = 0; /* Pointer to a new child page */
9088 Pgno pgnoChild = 0; /* Page number of the new child page */
9089 BtShared *pBt = pRoot->pBt; /* The BTree */
9090
9091 assert( pRoot->nOverflow>0 );
9092 assert( sqlite3_mutex_held(pBt->mutex) );
9093
9094 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
9095 ** page that will become the new right-child of pPage. Copy the contents
9096 ** of the node stored on pRoot into the new child page.
9097 */
9098 rc = sqlite3PagerWrite(pRoot->pDbPage);
9099 if( rc==SQLITE_OK ){
9100 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
9101 copyNodeContent(pRoot, pChild, &rc);
9102 if( ISAUTOVACUUM(pBt) ){
9103 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
9104 }
9105 }
9106 if( rc ){
9107 *ppChild = 0;
9108 releasePage(pChild);
9109 return rc;
9110 }
9111 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
9112 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
9113 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
9114
9115 TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno));
9116
9117 /* Copy the overflow cells from pRoot to pChild */
9118 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
9119 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
9120 memcpy(pChild->apOvfl, pRoot->apOvfl,
9121 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
9122 pChild->nOverflow = pRoot->nOverflow;
9123
9124 /* Zero the contents of pRoot. Then install pChild as the right-child. */
9125 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
9126 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
9127
9128 *ppChild = pChild;
9129 return SQLITE_OK;
9130}
9131
9132/*
9133** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
9134** on the same B-tree as pCur.
9135**
9136** This can occur if a database is corrupt with two or more SQL tables
9137** pointing to the same b-tree. If an insert occurs on one SQL table
9138** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
9139** table linked to the same b-tree. If the secondary insert causes a
9140** rebalance, that can change content out from under the cursor on the
9141** first SQL table, violating invariants on the first insert.
9142*/
9143static int anotherValidCursor(BtCursor *pCur){
9144 BtCursor *pOther;
9145 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
9146 if( pOther!=pCur
9147 && pOther->eState==CURSOR_VALID
9148 && pOther->pPage==pCur->pPage
9149 ){
9150 return SQLITE_CORRUPT_PAGE(pCur->pPage);
9151 }
9152 }
9153 return SQLITE_OK;
9154}
9155
9156/*
9157** The page that pCur currently points to has just been modified in
9158** some way. This function figures out if this modification means the
9159** tree needs to be balanced, and if so calls the appropriate balancing
9160** routine. Balancing routines are:
9161**
9162** balance_quick()
9163** balance_deeper()
9164** balance_nonroot()
9165*/
9166static int balance(BtCursor *pCur){
9167 int rc = SQLITE_OK;
9168 u8 aBalanceQuickSpace[13];
9169 u8 *pFree = 0;
9170
9171 VVA_ONLY( int balance_quick_called = 0 );
9172 VVA_ONLY( int balance_deeper_called = 0 );
9173
9174 do {
9175 int iPage;
9176 MemPage *pPage = pCur->pPage;
9177
9178 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
9179 if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
9180 /* No rebalance required as long as:
9181 ** (1) There are no overflow cells
9182 ** (2) The amount of free space on the page is less than 2/3rds of
9183 ** the total usable space on the page. */
9184 break;
9185 }else if( (iPage = pCur->iPage)==0 ){
9186 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
9187 /* The root page of the b-tree is overfull. In this case call the
9188 ** balance_deeper() function to create a new child for the root-page
9189 ** and copy the current contents of the root-page to it. The
9190 ** next iteration of the do-loop will balance the child page.
9191 */
9192 assert( balance_deeper_called==0 );
9193 VVA_ONLY( balance_deeper_called++ );
9194 rc = balance_deeper(pPage, &pCur->apPage[1]);
9195 if( rc==SQLITE_OK ){
9196 pCur->iPage = 1;
9197 pCur->ix = 0;
9198 pCur->aiIdx[0] = 0;
9199 pCur->apPage[0] = pPage;
9200 pCur->pPage = pCur->apPage[1];
9201 assert( pCur->pPage->nOverflow );
9202 }
9203 }else{
9204 break;
9205 }
9206 }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
9207 /* The page being written is not a root page, and there is currently
9208 ** more than one reference to it. This only happens if the page is one
9209 ** of its own ancestor pages. Corruption. */
9210 rc = SQLITE_CORRUPT_PAGE(pPage);
9211 }else{
9212 MemPage * const pParent = pCur->apPage[iPage-1];
9213 int const iIdx = pCur->aiIdx[iPage-1];
9214
9215 rc = sqlite3PagerWrite(pParent->pDbPage);
9216 if( rc==SQLITE_OK && pParent->nFree<0 ){
9217 rc = btreeComputeFreeSpace(pParent);
9218 }
9219 if( rc==SQLITE_OK ){
9220#ifndef SQLITE_OMIT_QUICKBALANCE
9221 if( pPage->intKeyLeaf
9222 && pPage->nOverflow==1
9223 && pPage->aiOvfl[0]==pPage->nCell
9224 && pParent->pgno!=1
9225 && pParent->nCell==iIdx
9226 ){
9227 /* Call balance_quick() to create a new sibling of pPage on which
9228 ** to store the overflow cell. balance_quick() inserts a new cell
9229 ** into pParent, which may cause pParent overflow. If this
9230 ** happens, the next iteration of the do-loop will balance pParent
9231 ** use either balance_nonroot() or balance_deeper(). Until this
9232 ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
9233 ** buffer.
9234 **
9235 ** The purpose of the following assert() is to check that only a
9236 ** single call to balance_quick() is made for each call to this
9237 ** function. If this were not verified, a subtle bug involving reuse
9238 ** of the aBalanceQuickSpace[] might sneak in.
9239 */
9240 assert( balance_quick_called==0 );
9241 VVA_ONLY( balance_quick_called++ );
9242 rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
9243 }else
9244#endif
9245 {
9246 /* In this case, call balance_nonroot() to redistribute cells
9247 ** between pPage and up to 2 of its sibling pages. This involves
9248 ** modifying the contents of pParent, which may cause pParent to
9249 ** become overfull or underfull. The next iteration of the do-loop
9250 ** will balance the parent page to correct this.
9251 **
9252 ** If the parent page becomes overfull, the overflow cell or cells
9253 ** are stored in the pSpace buffer allocated immediately below.
9254 ** A subsequent iteration of the do-loop will deal with this by
9255 ** calling balance_nonroot() (balance_deeper() may be called first,
9256 ** but it doesn't deal with overflow cells - just moves them to a
9257 ** different page). Once this subsequent call to balance_nonroot()
9258 ** has completed, it is safe to release the pSpace buffer used by
9259 ** the previous call, as the overflow cell data will have been
9260 ** copied either into the body of a database page or into the new
9261 ** pSpace buffer passed to the latter call to balance_nonroot().
9262 */
9263 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
9264 rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
9265 pCur->hints&BTREE_BULKLOAD);
9266 if( pFree ){
9267 /* If pFree is not NULL, it points to the pSpace buffer used
9268 ** by a previous call to balance_nonroot(). Its contents are
9269 ** now stored either on real database pages or within the
9270 ** new pSpace buffer, so it may be safely freed here. */
9271 sqlite3PageFree(pFree);
9272 }
9273
9274 /* The pSpace buffer will be freed after the next call to
9275 ** balance_nonroot(), or just before this function returns, whichever
9276 ** comes first. */
9277 pFree = pSpace;
9278 }
9279 }
9280
9281 pPage->nOverflow = 0;
9282
9283 /* The next iteration of the do-loop balances the parent page. */
9284 releasePage(pPage);
9285 pCur->iPage--;
9286 assert( pCur->iPage>=0 );
9287 pCur->pPage = pCur->apPage[pCur->iPage];
9288 }
9289 }while( rc==SQLITE_OK );
9290
9291 if( pFree ){
9292 sqlite3PageFree(pFree);
9293 }
9294 return rc;
9295}
9296
9297/* Overwrite content from pX into pDest. Only do the write if the
9298** content is different from what is already there.
9299*/
9300static int btreeOverwriteContent(
9301 MemPage *pPage, /* MemPage on which writing will occur */
9302 u8 *pDest, /* Pointer to the place to start writing */
9303 const BtreePayload *pX, /* Source of data to write */
9304 int iOffset, /* Offset of first byte to write */
9305 int iAmt /* Number of bytes to be written */
9306){
9307 int nData = pX->nData - iOffset;
9308 if( nData<=0 ){
9309 /* Overwriting with zeros */
9310 int i;
9311 for(i=0; i<iAmt && pDest[i]==0; i++){}
9312 if( i<iAmt ){
9313 int rc = sqlite3PagerWrite(pPage->pDbPage);
9314 if( rc ) return rc;
9315 memset(pDest + i, 0, iAmt - i);
9316 }
9317 }else{
9318 if( nData<iAmt ){
9319 /* Mixed read data and zeros at the end. Make a recursive call
9320 ** to write the zeros then fall through to write the real data */
9321 int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
9322 iAmt-nData);
9323 if( rc ) return rc;
9324 iAmt = nData;
9325 }
9326 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
9327 int rc = sqlite3PagerWrite(pPage->pDbPage);
9328 if( rc ) return rc;
9329 /* In a corrupt database, it is possible for the source and destination
9330 ** buffers to overlap. This is harmless since the database is already
9331 ** corrupt but it does cause valgrind and ASAN warnings. So use
9332 ** memmove(). */
9333 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
9334 }
9335 }
9336 return SQLITE_OK;
9337}
9338
9339/*
9340** Overwrite the cell that cursor pCur is pointing to with fresh content
9341** contained in pX. In this variant, pCur is pointing to an overflow
9342** cell.
9343*/
9344static SQLITE_NOINLINE int btreeOverwriteOverflowCell(
9345 BtCursor *pCur, /* Cursor pointing to cell to overwrite */
9346 const BtreePayload *pX /* Content to write into the cell */
9347){
9348 int iOffset; /* Next byte of pX->pData to write */
9349 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9350 int rc; /* Return code */
9351 MemPage *pPage = pCur->pPage; /* Page being written */
9352 BtShared *pBt; /* Btree */
9353 Pgno ovflPgno; /* Next overflow page to write */
9354 u32 ovflPageSize; /* Size to write on overflow page */
9355
9356 assert( pCur->info.nLocal<nTotal ); /* pCur is an overflow cell */
9357
9358 /* Overwrite the local portion first */
9359 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9360 0, pCur->info.nLocal);
9361 if( rc ) return rc;
9362
9363 /* Now overwrite the overflow pages */
9364 iOffset = pCur->info.nLocal;
9365 assert( nTotal>=0 );
9366 assert( iOffset>=0 );
9367 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
9368 pBt = pPage->pBt;
9369 ovflPageSize = pBt->usableSize - 4;
9370 do{
9371 rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
9372 if( rc ) return rc;
9373 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
9374 rc = SQLITE_CORRUPT_PAGE(pPage);
9375 }else{
9376 if( iOffset+ovflPageSize<(u32)nTotal ){
9377 ovflPgno = get4byte(pPage->aData);
9378 }else{
9379 ovflPageSize = nTotal - iOffset;
9380 }
9381 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
9382 iOffset, ovflPageSize);
9383 }
9384 sqlite3PagerUnref(pPage->pDbPage);
9385 if( rc ) return rc;
9386 iOffset += ovflPageSize;
9387 }while( iOffset<nTotal );
9388 return SQLITE_OK;
9389}
9390
9391/*
9392** Overwrite the cell that cursor pCur is pointing to with fresh content
9393** contained in pX.
9394*/
9395static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
9396 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
9397 MemPage *pPage = pCur->pPage; /* Page being written */
9398
9399 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
9400 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
9401 ){
9402 return SQLITE_CORRUPT_PAGE(pPage);
9403 }
9404 if( pCur->info.nLocal==nTotal ){
9405 /* The entire cell is local */
9406 return btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
9407 0, pCur->info.nLocal);
9408 }else{
9409 /* The cell contains overflow content */
9410 return btreeOverwriteOverflowCell(pCur, pX);
9411 }
9412}
9413
9414
9415/*
9416** Insert a new record into the BTree. The content of the new record
9417** is described by the pX object. The pCur cursor is used only to
9418** define what table the record should be inserted into, and is left
9419** pointing at a random location.
9420**
9421** For a table btree (used for rowid tables), only the pX.nKey value of
9422** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
9423** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
9424** hold the content of the row.
9425**
9426** For an index btree (used for indexes and WITHOUT ROWID tables), the
9427** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
9428** pX.pData,nData,nZero fields must be zero.
9429**
9430** If the seekResult parameter is non-zero, then a successful call to
9431** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
9432** been performed. In other words, if seekResult!=0 then the cursor
9433** is currently pointing to a cell that will be adjacent to the cell
9434** to be inserted. If seekResult<0 then pCur points to a cell that is
9435** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
9436** that is larger than (pKey,nKey).
9437**
9438** If seekResult==0, that means pCur is pointing at some unknown location.
9439** In that case, this routine must seek the cursor to the correct insertion
9440** point for (pKey,nKey) before doing the insertion. For index btrees,
9441** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
9442** key values and pX->aMem can be used instead of pX->pKey to avoid having
9443** to decode the key.
9444*/
9445int sqlite3BtreeInsert(
9446 BtCursor *pCur, /* Insert data into the table of this cursor */
9447 const BtreePayload *pX, /* Content of the row to be inserted */
9448 int flags, /* True if this is likely an append */
9449 int seekResult /* Result of prior IndexMoveto() call */
9450){
9451 int rc;
9452 int loc = seekResult; /* -1: before desired location +1: after */
9453 int szNew = 0;
9454 int idx;
9455 MemPage *pPage;
9456 Btree *p = pCur->pBtree;
9457 unsigned char *oldCell;
9458 unsigned char *newCell = 0;
9459
9460 assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND|BTREE_PREFORMAT))==flags );
9461 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
9462
9463 /* Save the positions of any other cursors open on this table.
9464 **
9465 ** In some cases, the call to btreeMoveto() below is a no-op. For
9466 ** example, when inserting data into a table with auto-generated integer
9467 ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
9468 ** integer key to use. It then calls this function to actually insert the
9469 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
9470 ** that the cursor is already where it needs to be and returns without
9471 ** doing any work. To avoid thwarting these optimizations, it is important
9472 ** not to clear the cursor here.
9473 */
9474 if( pCur->curFlags & BTCF_Multiple ){
9475 rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur);
9476 if( rc ) return rc;
9477 if( loc && pCur->iPage<0 ){
9478 /* This can only happen if the schema is corrupt such that there is more
9479 ** than one table or index with the same root page as used by the cursor.
9480 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
9481 ** the schema was loaded. This cannot be asserted though, as a user might
9482 ** set the flag, load the schema, and then unset the flag. */
9483 return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot);
9484 }
9485 }
9486
9487 /* Ensure that the cursor is not in the CURSOR_FAULT state and that it
9488 ** points to a valid cell.
9489 */
9490 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9491 testcase( pCur->eState==CURSOR_REQUIRESEEK );
9492 testcase( pCur->eState==CURSOR_FAULT );
9493 rc = moveToRoot(pCur);
9494 if( rc && rc!=SQLITE_EMPTY ) return rc;
9495 loc = 0; /* Indicate the the cursor is not in a known position */
9496 }
9497
9498 assert( cursorOwnsBtShared(pCur) );
9499 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
9500 && p->pBt->inTransaction==TRANS_WRITE
9501 && (p->pBt->btsFlags & BTS_READ_ONLY)==0 );
9502 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9503
9504 /* Assert that the caller has been consistent. If this cursor was opened
9505 ** expecting an index b-tree, then the caller should be inserting blob
9506 ** keys with no associated data. If the cursor was opened expecting an
9507 ** intkey table, the caller should be inserting integer keys with a
9508 ** blob of associated data. */
9509 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
9510
9511 if( pCur->pKeyInfo==0 ){
9512 assert( pX->pKey==0 );
9513 /* If this is an insert into a table b-tree, invalidate any incrblob
9514 ** cursors open on the row being replaced */
9515 if( p->hasIncrblobCur ){
9516 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
9517 }
9518
9519 /* If BTREE_SAVEPOSITION is set and seekResult is non-zero and
9520 ** if we didn't have to reposition the cursor initially, then
9521 ** the cursor must already be pointing to a row with the same
9522 ** key as the new entry being inserted. Verify that this is so.
9523 */
9524#ifdef SQLITE_DEBUG
9525 if( (flags & BTREE_SAVEPOSITION)!=0 && loc!=0 ){
9526 assert( pCur->curFlags & BTCF_ValidNKey );
9527 assert( pX->nKey==pCur->info.nKey );
9528 assert( loc==0 );
9529 }
9530#endif
9531
9532 /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
9533 ** that the cursor is not pointing to a row to be overwritten.
9534 ** So do a complete check.
9535 */
9536 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
9537 /* The cursor is pointing to the entry that is to be
9538 ** overwritten */
9539 assert( pX->nData>=0 && pX->nZero>=0 );
9540 if( pCur->info.nSize!=0
9541 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
9542 ){
9543 /* New entry is the same size as the old. Do an overwrite */
9544 return btreeOverwriteCell(pCur, pX);
9545 }
9546 assert( loc==0 );
9547 }else if( loc==0 ){
9548 /* The cursor is *not* pointing to the cell to be overwritten, nor
9549 ** to an adjacent cell. Move the cursor so that it is pointing either
9550 ** to the cell to be overwritten or an adjacent cell.
9551 */
9552 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
9553 (flags & BTREE_APPEND)!=0, &loc);
9554 if( rc ) return rc;
9555 }
9556 }else{
9557 /* This is an index or a WITHOUT ROWID table */
9558
9559 /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
9560 ** to a row with the same key as the new entry being inserted.
9561 */
9562 assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
9563
9564 /* If the cursor is not already pointing either to the cell to be
9565 ** overwritten, or if a new cell is being inserted, if the cursor is
9566 ** not pointing to an immediately adjacent cell, then move the cursor
9567 ** so that it does.
9568 */
9569 if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
9570 if( pX->nMem ){
9571 UnpackedRecord r;
9572 r.pKeyInfo = pCur->pKeyInfo;
9573 r.aMem = pX->aMem;
9574 r.nField = pX->nMem;
9575 r.default_rc = 0;
9576 r.eqSeen = 0;
9577 rc = sqlite3BtreeIndexMoveto(pCur, &r, &loc);
9578 }else{
9579 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
9580 (flags & BTREE_APPEND)!=0, &loc);
9581 }
9582 if( rc ) return rc;
9583 }
9584
9585 /* If the cursor is currently pointing to an entry to be overwritten
9586 ** and the new content is the same as as the old, then use the
9587 ** overwrite optimization.
9588 */
9589 if( loc==0 ){
9590 getCellInfo(pCur);
9591 if( pCur->info.nKey==pX->nKey ){
9592 BtreePayload x2;
9593 x2.pData = pX->pKey;
9594 x2.nData = (int)pX->nKey; assert( pX->nKey<=0x7fffffff );
9595 x2.nZero = 0;
9596 return btreeOverwriteCell(pCur, &x2);
9597 }
9598 }
9599 }
9600 assert( pCur->eState==CURSOR_VALID
9601 || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB );
9602
9603 pPage = pCur->pPage;
9604 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
9605 assert( pPage->leaf || !pPage->intKey );
9606 if( pPage->nFree<0 ){
9607 if( NEVER(pCur->eState>CURSOR_INVALID) ){
9608 /* ^^^^^--- due to the moveToRoot() call above */
9609 rc = SQLITE_CORRUPT_PAGE(pPage);
9610 }else{
9611 rc = btreeComputeFreeSpace(pPage);
9612 }
9613 if( rc ) return rc;
9614 }
9615
9616 TRACE(("INSERT: table=%u nkey=%lld ndata=%u page=%u %s\n",
9617 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
9618 loc==0 ? "overwrite" : "new entry"));
9619 assert( pPage->isInit || CORRUPT_DB );
9620 newCell = p->pBt->pTmpSpace;
9621 assert( newCell!=0 );
9622 assert( BTREE_PREFORMAT==OPFLAG_PREFORMAT );
9623 if( flags & BTREE_PREFORMAT ){
9624 rc = SQLITE_OK;
9625 szNew = p->pBt->nPreformatSize;
9626 if( szNew<4 ){
9627 szNew = 4;
9628 newCell[3] = 0;
9629 }
9630 if( ISAUTOVACUUM(p->pBt) && szNew>pPage->maxLocal ){
9631 CellInfo info;
9632 pPage->xParseCell(pPage, newCell, &info);
9633 if( info.nPayload!=info.nLocal ){
9634 Pgno ovfl = get4byte(&newCell[szNew-4]);
9635 ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
9636 if( NEVER(rc) ) goto end_insert;
9637 }
9638 }
9639 }else{
9640 rc = fillInCell(pPage, newCell, pX, &szNew);
9641 if( rc ) goto end_insert;
9642 }
9643 assert( szNew==pPage->xCellSize(pPage, newCell) );
9644 assert( szNew <= MX_CELL_SIZE(p->pBt) );
9645 idx = pCur->ix;
9646 pCur->info.nSize = 0;
9647 if( loc==0 ){
9648 CellInfo info;
9649 assert( idx>=0 );
9650 if( idx>=pPage->nCell ){
9651 return SQLITE_CORRUPT_PAGE(pPage);
9652 }
9653 rc = sqlite3PagerWrite(pPage->pDbPage);
9654 if( rc ){
9655 goto end_insert;
9656 }
9657 oldCell = findCell(pPage, idx);
9658 if( !pPage->leaf ){
9659 memcpy(newCell, oldCell, 4);
9660 }
9661 BTREE_CLEAR_CELL(rc, pPage, oldCell, info);
9662 testcase( pCur->curFlags & BTCF_ValidOvfl );
9663 invalidateOverflowCache(pCur);
9664 if( info.nSize==szNew && info.nLocal==info.nPayload
9665 && (!ISAUTOVACUUM(p->pBt) || szNew<pPage->minLocal)
9666 ){
9667 /* Overwrite the old cell with the new if they are the same size.
9668 ** We could also try to do this if the old cell is smaller, then add
9669 ** the leftover space to the free list. But experiments show that
9670 ** doing that is no faster then skipping this optimization and just
9671 ** calling dropCell() and insertCell().
9672 **
9673 ** This optimization cannot be used on an autovacuum database if the
9674 ** new entry uses overflow pages, as the insertCell() call below is
9675 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
9676 assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
9677 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
9678 return SQLITE_CORRUPT_PAGE(pPage);
9679 }
9680 if( oldCell+szNew > pPage->aDataEnd ){
9681 return SQLITE_CORRUPT_PAGE(pPage);
9682 }
9683 memcpy(oldCell, newCell, szNew);
9684 return SQLITE_OK;
9685 }
9686 dropCell(pPage, idx, info.nSize, &rc);
9687 if( rc ) goto end_insert;
9688 }else if( loc<0 && pPage->nCell>0 ){
9689 assert( pPage->leaf );
9690 idx = ++pCur->ix;
9691 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
9692 }else{
9693 assert( pPage->leaf );
9694 }
9695 rc = insertCellFast(pPage, idx, newCell, szNew);
9696 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
9697 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
9698
9699 /* If no error has occurred and pPage has an overflow cell, call balance()
9700 ** to redistribute the cells within the tree. Since balance() may move
9701 ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
9702 ** variables.
9703 **
9704 ** Previous versions of SQLite called moveToRoot() to move the cursor
9705 ** back to the root page as balance() used to invalidate the contents
9706 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
9707 ** set the cursor state to "invalid". This makes common insert operations
9708 ** slightly faster.
9709 **
9710 ** There is a subtle but important optimization here too. When inserting
9711 ** multiple records into an intkey b-tree using a single cursor (as can
9712 ** happen while processing an "INSERT INTO ... SELECT" statement), it
9713 ** is advantageous to leave the cursor pointing to the last entry in
9714 ** the b-tree if possible. If the cursor is left pointing to the last
9715 ** entry in the table, and the next row inserted has an integer key
9716 ** larger than the largest existing key, it is possible to insert the
9717 ** row without seeking the cursor. This can be a big performance boost.
9718 */
9719 if( pPage->nOverflow ){
9720 assert( rc==SQLITE_OK );
9721 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
9722 rc = balance(pCur);
9723
9724 /* Must make sure nOverflow is reset to zero even if the balance()
9725 ** fails. Internal data structure corruption will result otherwise.
9726 ** Also, set the cursor state to invalid. This stops saveCursorPosition()
9727 ** from trying to save the current position of the cursor. */
9728 pCur->pPage->nOverflow = 0;
9729 pCur->eState = CURSOR_INVALID;
9730 if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
9731 btreeReleaseAllCursorPages(pCur);
9732 if( pCur->pKeyInfo ){
9733 assert( pCur->pKey==0 );
9734 pCur->pKey = sqlite3Malloc( pX->nKey );
9735 if( pCur->pKey==0 ){
9736 rc = SQLITE_NOMEM;
9737 }else{
9738 memcpy(pCur->pKey, pX->pKey, pX->nKey);
9739 }
9740 }
9741 pCur->eState = CURSOR_REQUIRESEEK;
9742 pCur->nKey = pX->nKey;
9743 }
9744 }
9745 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
9746
9747end_insert:
9748 return rc;
9749}
9750
9751/*
9752** This function is used as part of copying the current row from cursor
9753** pSrc into cursor pDest. If the cursors are open on intkey tables, then
9754** parameter iKey is used as the rowid value when the record is copied
9755** into pDest. Otherwise, the record is copied verbatim.
9756**
9757** This function does not actually write the new value to cursor pDest.
9758** Instead, it creates and populates any required overflow pages and
9759** writes the data for the new cell into the BtShared.pTmpSpace buffer
9760** for the destination database. The size of the cell, in bytes, is left
9761** in BtShared.nPreformatSize. The caller completes the insertion by
9762** calling sqlite3BtreeInsert() with the BTREE_PREFORMAT flag specified.
9763**
9764** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
9765*/
9766int sqlite3BtreeTransferRow(BtCursor *pDest, BtCursor *pSrc, i64 iKey){
9767 BtShared *pBt = pDest->pBt;
9768 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
9769 const u8 *aIn; /* Pointer to next input buffer */
9770 u32 nIn; /* Size of input buffer aIn[] */
9771 u32 nRem; /* Bytes of data still to copy */
9772
9773 getCellInfo(pSrc);
9774 if( pSrc->info.nPayload<0x80 ){
9775 *(aOut++) = (u8)pSrc->info.nPayload;
9776 }else{
9777 aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
9778 }
9779 if( pDest->pKeyInfo==0 ) aOut += sqlite3PutVarint(aOut, iKey);
9780 nIn = pSrc->info.nLocal;
9781 aIn = pSrc->info.pPayload;
9782 if( aIn+nIn>pSrc->pPage->aDataEnd ){
9783 return SQLITE_CORRUPT_PAGE(pSrc->pPage);
9784 }
9785 nRem = pSrc->info.nPayload;
9786 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
9787 memcpy(aOut, aIn, nIn);
9788 pBt->nPreformatSize = nIn + (int)(aOut - pBt->pTmpSpace);
9789 return SQLITE_OK;
9790 }else{
9791 int rc = SQLITE_OK;
9792 Pager *pSrcPager = pSrc->pBt->pPager;
9793 u8 *pPgnoOut = 0;
9794 Pgno ovflIn = 0;
9795 DbPage *pPageIn = 0;
9796 MemPage *pPageOut = 0;
9797 u32 nOut; /* Size of output buffer aOut[] */
9798
9799 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
9800 pBt->nPreformatSize = (int)nOut + (int)(aOut - pBt->pTmpSpace);
9801 if( nOut<pSrc->info.nPayload ){
9802 pPgnoOut = &aOut[nOut];
9803 pBt->nPreformatSize += 4;
9804 }
9805
9806 if( nRem>nIn ){
9807 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
9808 return SQLITE_CORRUPT_PAGE(pSrc->pPage);
9809 }
9810 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
9811 }
9812
9813 do {
9814 nRem -= nOut;
9815 do{
9816 assert( nOut>0 );
9817 if( nIn>0 ){
9818 int nCopy = MIN(nOut, nIn);
9819 memcpy(aOut, aIn, nCopy);
9820 nOut -= nCopy;
9821 nIn -= nCopy;
9822 aOut += nCopy;
9823 aIn += nCopy;
9824 }
9825 if( nOut>0 ){
9826 sqlite3PagerUnref(pPageIn);
9827 pPageIn = 0;
9828 rc = sqlite3PagerGet(pSrcPager, ovflIn, &pPageIn, PAGER_GET_READONLY);
9829 if( rc==SQLITE_OK ){
9830 aIn = (const u8*)sqlite3PagerGetData(pPageIn);
9831 ovflIn = get4byte(aIn);
9832 aIn += 4;
9833 nIn = pSrc->pBt->usableSize - 4;
9834 }
9835 }
9836 }while( rc==SQLITE_OK && nOut>0 );
9837
9838 if( rc==SQLITE_OK && nRem>0 && ALWAYS(pPgnoOut) ){
9839 Pgno pgnoNew = 0; /* Prevent harmless static-analyzer warning */
9840 MemPage *pNew = 0;
9841 rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
9842 put4byte(pPgnoOut, pgnoNew);
9843 if( ISAUTOVACUUM(pBt) && pPageOut ){
9844 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
9845 }
9846 releasePage(pPageOut);
9847 pPageOut = pNew;
9848 if( pPageOut ){
9849 pPgnoOut = pPageOut->aData;
9850 put4byte(pPgnoOut, 0);
9851 aOut = &pPgnoOut[4];
9852 nOut = MIN(pBt->usableSize - 4, nRem);
9853 }
9854 }
9855 }while( nRem>0 && rc==SQLITE_OK );
9856
9857 releasePage(pPageOut);
9858 sqlite3PagerUnref(pPageIn);
9859 return rc;
9860 }
9861}
9862
9863/*
9864** Delete the entry that the cursor is pointing to.
9865**
9866** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
9867** the cursor is left pointing at an arbitrary location after the delete.
9868** But if that bit is set, then the cursor is left in a state such that
9869** the next call to BtreeNext() or BtreePrev() moves it to the same row
9870** as it would have been on if the call to BtreeDelete() had been omitted.
9871**
9872** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
9873** associated with a single table entry and its indexes. Only one of those
9874** deletes is considered the "primary" delete. The primary delete occurs
9875** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
9876** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
9877** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
9878** but which might be used by alternative storage engines.
9879*/
9880int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
9881 Btree *p = pCur->pBtree;
9882 BtShared *pBt = p->pBt;
9883 int rc; /* Return code */
9884 MemPage *pPage; /* Page to delete cell from */
9885 unsigned char *pCell; /* Pointer to cell to delete */
9886 int iCellIdx; /* Index of cell to delete */
9887 int iCellDepth; /* Depth of node containing pCell */
9888 CellInfo info; /* Size of the cell being deleted */
9889 u8 bPreserve; /* Keep cursor valid. 2 for CURSOR_SKIPNEXT */
9890
9891 assert( cursorOwnsBtShared(pCur) );
9892 assert( pBt->inTransaction==TRANS_WRITE );
9893 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
9894 assert( pCur->curFlags & BTCF_WriteFlag );
9895 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
9896 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
9897 assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
9898 if( pCur->eState!=CURSOR_VALID ){
9899 if( pCur->eState>=CURSOR_REQUIRESEEK ){
9900 rc = btreeRestoreCursorPosition(pCur);
9901 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
9902 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
9903 }else{
9904 return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot);
9905 }
9906 }
9907 assert( pCur->eState==CURSOR_VALID );
9908
9909 iCellDepth = pCur->iPage;
9910 iCellIdx = pCur->ix;
9911 pPage = pCur->pPage;
9912 if( pPage->nCell<=iCellIdx ){
9913 return SQLITE_CORRUPT_PAGE(pPage);
9914 }
9915 pCell = findCell(pPage, iCellIdx);
9916 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
9917 return SQLITE_CORRUPT_PAGE(pPage);
9918 }
9919 if( pCell<&pPage->aCellIdx[pPage->nCell] ){
9920 return SQLITE_CORRUPT_PAGE(pPage);
9921 }
9922
9923 /* If the BTREE_SAVEPOSITION bit is on, then the cursor position must
9924 ** be preserved following this delete operation. If the current delete
9925 ** will cause a b-tree rebalance, then this is done by saving the cursor
9926 ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
9927 ** returning.
9928 **
9929 ** If the current delete will not cause a rebalance, then the cursor
9930 ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
9931 ** before or after the deleted entry.
9932 **
9933 ** The bPreserve value records which path is required:
9934 **
9935 ** bPreserve==0 Not necessary to save the cursor position
9936 ** bPreserve==1 Use CURSOR_REQUIRESEEK to save the cursor position
9937 ** bPreserve==2 Cursor won't move. Set CURSOR_SKIPNEXT.
9938 */
9939 bPreserve = (flags & BTREE_SAVEPOSITION)!=0;
9940 if( bPreserve ){
9941 if( !pPage->leaf
9942 || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
9943 (int)(pBt->usableSize*2/3)
9944 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
9945 ){
9946 /* A b-tree rebalance will be required after deleting this entry.
9947 ** Save the cursor key. */
9948 rc = saveCursorKey(pCur);
9949 if( rc ) return rc;
9950 }else{
9951 bPreserve = 2;
9952 }
9953 }
9954
9955 /* If the page containing the entry to delete is not a leaf page, move
9956 ** the cursor to the largest entry in the tree that is smaller than
9957 ** the entry being deleted. This cell will replace the cell being deleted
9958 ** from the internal node. The 'previous' entry is used for this instead
9959 ** of the 'next' entry, as the previous entry is always a part of the
9960 ** sub-tree headed by the child page of the cell being deleted. This makes
9961 ** balancing the tree following the delete operation easier. */
9962 if( !pPage->leaf ){
9963 rc = sqlite3BtreePrevious(pCur, 0);
9964 assert( rc!=SQLITE_DONE );
9965 if( rc ) return rc;
9966 }
9967
9968 /* Save the positions of any other cursors open on this table before
9969 ** making any modifications. */
9970 if( pCur->curFlags & BTCF_Multiple ){
9971 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
9972 if( rc ) return rc;
9973 }
9974
9975 /* If this is a delete operation to remove a row from a table b-tree,
9976 ** invalidate any incrblob cursors open on the row being deleted. */
9977 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
9978 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
9979 }
9980
9981 /* Make the page containing the entry to be deleted writable. Then free any
9982 ** overflow pages associated with the entry and finally remove the cell
9983 ** itself from within the page. */
9984 rc = sqlite3PagerWrite(pPage->pDbPage);
9985 if( rc ) return rc;
9986 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
9987 dropCell(pPage, iCellIdx, info.nSize, &rc);
9988 if( rc ) return rc;
9989
9990 /* If the cell deleted was not located on a leaf page, then the cursor
9991 ** is currently pointing to the largest entry in the sub-tree headed
9992 ** by the child-page of the cell that was just deleted from an internal
9993 ** node. The cell from the leaf node needs to be moved to the internal
9994 ** node to replace the deleted cell. */
9995 if( !pPage->leaf ){
9996 MemPage *pLeaf = pCur->pPage;
9997 int nCell;
9998 Pgno n;
9999 unsigned char *pTmp;
10000
10001 if( pLeaf->nFree<0 ){
10002 rc = btreeComputeFreeSpace(pLeaf);
10003 if( rc ) return rc;
10004 }
10005 if( iCellDepth<pCur->iPage-1 ){
10006 n = pCur->apPage[iCellDepth+1]->pgno;
10007 }else{
10008 n = pCur->pPage->pgno;
10009 }
10010 pCell = findCell(pLeaf, pLeaf->nCell-1);
10011 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_PAGE(pLeaf);
10012 nCell = pLeaf->xCellSize(pLeaf, pCell);
10013 assert( MX_CELL_SIZE(pBt) >= nCell );
10014 pTmp = pBt->pTmpSpace;
10015 assert( pTmp!=0 );
10016 rc = sqlite3PagerWrite(pLeaf->pDbPage);
10017 if( rc==SQLITE_OK ){
10018 rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4-(pCell[0]==2), pTmp, n);
10019 }
10020 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
10021 if( rc ) return rc;
10022 }
10023
10024 /* Balance the tree. If the entry deleted was located on a leaf page,
10025 ** then the cursor still points to that page. In this case the first
10026 ** call to balance() repairs the tree, and the if(...) condition is
10027 ** never true.
10028 **
10029 ** Otherwise, if the entry deleted was on an internal node page, then
10030 ** pCur is pointing to the leaf page from which a cell was removed to
10031 ** replace the cell deleted from the internal node. This is slightly
10032 ** tricky as the leaf node may be underfull, and the internal node may
10033 ** be either under or overfull. In this case run the balancing algorithm
10034 ** on the leaf node first. If the balance proceeds far enough up the
10035 ** tree that we can be sure that any problem in the internal node has
10036 ** been corrected, so be it. Otherwise, after balancing the leaf node,
10037 ** walk the cursor up the tree to the internal node and balance it as
10038 ** well. */
10039 assert( pCur->pPage->nOverflow==0 );
10040 assert( pCur->pPage->nFree>=0 );
10041 if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
10042 /* Optimization: If the free space is less than 2/3rds of the page,
10043 ** then balance() will always be a no-op. No need to invoke it. */
10044 rc = SQLITE_OK;
10045 }else{
10046 rc = balance(pCur);
10047 }
10048 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
10049 releasePageNotNull(pCur->pPage);
10050 pCur->iPage--;
10051 while( pCur->iPage>iCellDepth ){
10052 releasePage(pCur->apPage[pCur->iPage--]);
10053 }
10054 pCur->pPage = pCur->apPage[pCur->iPage];
10055 rc = balance(pCur);
10056 }
10057
10058 if( rc==SQLITE_OK ){
10059 if( bPreserve>1 ){
10060 assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
10061 assert( pPage==pCur->pPage || CORRUPT_DB );
10062 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
10063 pCur->eState = CURSOR_SKIPNEXT;
10064 if( iCellIdx>=pPage->nCell ){
10065 pCur->skipNext = -1;
10066 pCur->ix = pPage->nCell-1;
10067 }else{
10068 pCur->skipNext = 1;
10069 }
10070 /* The pCur->info structure is currently populated with the details
10071 ** of the cell that was just removed. But pCur->ix now points to a
10072 ** different cell in the b-tree. So zero info.nSize here so that if
10073 ** saveCursorPosition() is called on this cursor it does not trust
10074 ** the contents of pCur->info. */
10075 pCur->info.nSize = 0;
10076 }else{
10077 rc = moveToRoot(pCur);
10078 if( bPreserve ){
10079 btreeReleaseAllCursorPages(pCur);
10080 pCur->eState = CURSOR_REQUIRESEEK;
10081 }
10082 if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
10083 }
10084 }
10085 return rc;
10086}
10087
10088/*
10089** Create a new BTree table. Write into *piTable the page
10090** number for the root page of the new table.
10091**
10092** The type of type is determined by the flags parameter. Only the
10093** following values of flags are currently in use. Other values for
10094** flags might not work:
10095**
10096** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
10097** BTREE_ZERODATA Used for SQL indices
10098*/
10099static int btreeCreateTable(Btree *p, Pgno *piTable, int createTabFlags){
10100 BtShared *pBt = p->pBt;
10101 MemPage *pRoot;
10102 Pgno pgnoRoot;
10103 int rc;
10104 int ptfFlags; /* Page-type flags for the root page of new table */
10105
10106 assert( sqlite3BtreeHoldsMutex(p) );
10107 assert( pBt->inTransaction==TRANS_WRITE );
10108 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
10109
10110#ifdef SQLITE_OMIT_AUTOVACUUM
10111 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
10112 if( rc ){
10113 return rc;
10114 }
10115#else
10116 if( pBt->autoVacuum ){
10117 Pgno pgnoMove; /* Move a page here to make room for the root-page */
10118 MemPage *pPageMove; /* The page to move to. */
10119
10120 /* Creating a new table may probably require moving an existing database
10121 ** to make room for the new tables root page. In case this page turns
10122 ** out to be an overflow page, delete all overflow page-map caches
10123 ** held by open cursors.
10124 */
10125 invalidateAllOverflowCache(pBt);
10126
10127 /* Read the value of meta[3] from the database to determine where the
10128 ** root page of the new table should go. meta[3] is the largest root-page
10129 ** created so far, so the new root-page is (meta[3]+1).
10130 */
10131 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
10132 if( pgnoRoot>btreePagecount(pBt) ){
10133 return SQLITE_CORRUPT_PGNO(pgnoRoot);
10134 }
10135 pgnoRoot++;
10136
10137 /* The new root-page may not be allocated on a pointer-map page, or the
10138 ** PENDING_BYTE page.
10139 */
10140 while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
10141 pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
10142 pgnoRoot++;
10143 }
10144 assert( pgnoRoot>=3 );
10145
10146 /* Allocate a page. The page that currently resides at pgnoRoot will
10147 ** be moved to the allocated page (unless the allocated page happens
10148 ** to reside at pgnoRoot).
10149 */
10150 rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
10151 if( rc!=SQLITE_OK ){
10152 return rc;
10153 }
10154
10155 if( pgnoMove!=pgnoRoot ){
10156 /* pgnoRoot is the page that will be used for the root-page of
10157 ** the new table (assuming an error did not occur). But we were
10158 ** allocated pgnoMove. If required (i.e. if it was not allocated
10159 ** by extending the file), the current page at position pgnoMove
10160 ** is already journaled.
10161 */
10162 u8 eType = 0;
10163 Pgno iPtrPage = 0;
10164
10165 /* Save the positions of any open cursors. This is required in
10166 ** case they are holding a reference to an xFetch reference
10167 ** corresponding to page pgnoRoot. */
10168 rc = saveAllCursors(pBt, 0, 0);
10169 releasePage(pPageMove);
10170 if( rc!=SQLITE_OK ){
10171 return rc;
10172 }
10173
10174 /* Move the page currently at pgnoRoot to pgnoMove. */
10175 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
10176 if( rc!=SQLITE_OK ){
10177 return rc;
10178 }
10179 rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
10180 if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
10181 rc = SQLITE_CORRUPT_PGNO(pgnoRoot);
10182 }
10183 if( rc!=SQLITE_OK ){
10184 releasePage(pRoot);
10185 return rc;
10186 }
10187 assert( eType!=PTRMAP_ROOTPAGE );
10188 assert( eType!=PTRMAP_FREEPAGE );
10189 rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
10190 releasePage(pRoot);
10191
10192 /* Obtain the page at pgnoRoot */
10193 if( rc!=SQLITE_OK ){
10194 return rc;
10195 }
10196 rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
10197 if( rc!=SQLITE_OK ){
10198 return rc;
10199 }
10200 rc = sqlite3PagerWrite(pRoot->pDbPage);
10201 if( rc!=SQLITE_OK ){
10202 releasePage(pRoot);
10203 return rc;
10204 }
10205 }else{
10206 pRoot = pPageMove;
10207 }
10208
10209 /* Update the pointer-map and meta-data with the new root-page number. */
10210 ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
10211 if( rc ){
10212 releasePage(pRoot);
10213 return rc;
10214 }
10215
10216 /* When the new root page was allocated, page 1 was made writable in
10217 ** order either to increase the database filesize, or to decrement the
10218 ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
10219 */
10220 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
10221 rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
10222 if( NEVER(rc) ){
10223 releasePage(pRoot);
10224 return rc;
10225 }
10226
10227 }else{
10228 rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
10229 if( rc ) return rc;
10230 }
10231#endif
10232 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
10233 if( createTabFlags & BTREE_INTKEY ){
10234 ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
10235 }else{
10236 ptfFlags = PTF_ZERODATA | PTF_LEAF;
10237 }
10238 zeroPage(pRoot, ptfFlags);
10239 sqlite3PagerUnref(pRoot->pDbPage);
10240 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
10241 *piTable = pgnoRoot;
10242 return SQLITE_OK;
10243}
10244int sqlite3BtreeCreateTable(Btree *p, Pgno *piTable, int flags){
10245 int rc;
10246 sqlite3BtreeEnter(p);
10247 rc = btreeCreateTable(p, piTable, flags);
10248 sqlite3BtreeLeave(p);
10249 return rc;
10250}
10251
10252/*
10253** Erase the given database page and all its children. Return
10254** the page to the freelist.
10255**
10256** The freePageFlag parameter serves a double role:
10257**
10258** * Bit 0 (freePageFlag&1) means that the page should be freed
10259** after it is cleared.
10260**
10261** * Bits 1-31 (freePageFlag>>1) is the depth of recursion. Use this
10262** to prevent a corrupt database file from recursing too deeply and
10263** overflowing the CPU stack.
10264*/
10265static int clearDatabasePage(
10266 BtShared *pBt, /* The BTree that contains the table */
10267 Pgno pgno, /* Page number to clear */
10268 int freePageFlag, /* bit 0: Deallocate page. Bits 1-31: depth */
10269 i64 *pnChange /* Add number of Cells freed to this counter */
10270){
10271 MemPage *pPage;
10272 int rc;
10273 unsigned char *pCell;
10274 int i;
10275 int hdr;
10276 CellInfo info;
10277
10278 assert( sqlite3_mutex_held(pBt->mutex) );
10279 if( pgno>btreePagecount(pBt) ){
10280 return SQLITE_CORRUPT_PGNO(pgno);
10281 }
10282 if( (freePageFlag>>1) > BTCURSOR_MAX_DEPTH ){
10283 return SQLITE_CORRUPT_PGNO(pgno);
10284 }
10285 rc = getAndInitPage(pBt, pgno, &pPage, 0);
10286 if( rc ) return rc;
10287 if( (pBt->openFlags & BTREE_SINGLE)==0
10288 && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
10289 ){
10290 rc = SQLITE_CORRUPT_PAGE(pPage);
10291 goto cleardatabasepage_out;
10292 }
10293 hdr = pPage->hdrOffset;
10294 for(i=0; i<pPage->nCell; i++){
10295 pCell = findCell(pPage, i);
10296 if( !pPage->leaf ){
10297 rc = clearDatabasePage(pBt, get4byte(pCell),
10298 (freePageFlag+2)|1, pnChange);
10299 if( rc ) goto cleardatabasepage_out;
10300 }
10301 BTREE_CLEAR_CELL(rc, pPage, pCell, info);
10302 if( rc ) goto cleardatabasepage_out;
10303 }
10304 if( !pPage->leaf ){
10305 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]),
10306 (freePageFlag+2)|1, pnChange);
10307 if( rc ) goto cleardatabasepage_out;
10308 if( pPage->intKey ) pnChange = 0;
10309 }
10310 if( pnChange ){
10311 testcase( !pPage->intKey );
10312 *pnChange += pPage->nCell;
10313 }
10314 if( (freePageFlag&1)!=0 ){
10315 freePage(pPage, &rc);
10316 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
10317 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
10318 }
10319
10320cleardatabasepage_out:
10321 releasePage(pPage);
10322 return rc;
10323}
10324
10325/*
10326** Delete all information from a single table in the database. iTable is
10327** the page number of the root of the table. After this routine returns,
10328** the root page is empty, but still exists.
10329**
10330** This routine will fail with SQLITE_LOCKED if there are any open
10331** read cursors on the table. Open write cursors are moved to the
10332** root of the table.
10333**
10334** If pnChange is not NULL, then the integer value pointed to by pnChange
10335** is incremented by the number of entries in the table.
10336*/
10337int sqlite3BtreeClearTable(Btree *p, int iTable, i64 *pnChange){
10338 int rc;
10339 BtShared *pBt = p->pBt;
10340 sqlite3BtreeEnter(p);
10341 assert( p->inTrans==TRANS_WRITE );
10342
10343 rc = saveAllCursors(pBt, (Pgno)iTable, 0);
10344
10345 if( SQLITE_OK==rc ){
10346 /* Invalidate all incrblob cursors open on table iTable (assuming iTable
10347 ** is the root of a table b-tree - if it is not, the following call is
10348 ** a no-op). */
10349 if( p->hasIncrblobCur ){
10350 invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
10351 }
10352 rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
10353 }
10354 sqlite3BtreeLeave(p);
10355 return rc;
10356}
10357
10358/*
10359** Delete all information from the single table that pCur is open on.
10360**
10361** This routine only work for pCur on an ephemeral table.
10362*/
10363int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
10364 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
10365}
10366
10367/*
10368** Erase all information in a table and add the root of the table to
10369** the freelist. Except, the root of the principle table (the one on
10370** page 1) is never added to the freelist.
10371**
10372** This routine will fail with SQLITE_LOCKED if there are any open
10373** cursors on the table.
10374**
10375** If AUTOVACUUM is enabled and the page at iTable is not the last
10376** root page in the database file, then the last root page
10377** in the database file is moved into the slot formerly occupied by
10378** iTable and that last slot formerly occupied by the last root page
10379** is added to the freelist instead of iTable. In this say, all
10380** root pages are kept at the beginning of the database file, which
10381** is necessary for AUTOVACUUM to work right. *piMoved is set to the
10382** page number that used to be the last root page in the file before
10383** the move. If no page gets moved, *piMoved is set to 0.
10384** The last root page is recorded in meta[3] and the value of
10385** meta[3] is updated by this procedure.
10386*/
10387static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
10388 int rc;
10389 MemPage *pPage = 0;
10390 BtShared *pBt = p->pBt;
10391
10392 assert( sqlite3BtreeHoldsMutex(p) );
10393 assert( p->inTrans==TRANS_WRITE );
10394 assert( iTable>=2 );
10395 if( iTable>btreePagecount(pBt) ){
10396 return SQLITE_CORRUPT_PGNO(iTable);
10397 }
10398
10399 rc = sqlite3BtreeClearTable(p, iTable, 0);
10400 if( rc ) return rc;
10401 rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
10402 if( NEVER(rc) ){
10403 releasePage(pPage);
10404 return rc;
10405 }
10406
10407 *piMoved = 0;
10408
10409#ifdef SQLITE_OMIT_AUTOVACUUM
10410 freePage(pPage, &rc);
10411 releasePage(pPage);
10412#else
10413 if( pBt->autoVacuum ){
10414 Pgno maxRootPgno;
10415 sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
10416
10417 if( iTable==maxRootPgno ){
10418 /* If the table being dropped is the table with the largest root-page
10419 ** number in the database, put the root page on the free list.
10420 */
10421 freePage(pPage, &rc);
10422 releasePage(pPage);
10423 if( rc!=SQLITE_OK ){
10424 return rc;
10425 }
10426 }else{
10427 /* The table being dropped does not have the largest root-page
10428 ** number in the database. So move the page that does into the
10429 ** gap left by the deleted root-page.
10430 */
10431 MemPage *pMove;
10432 releasePage(pPage);
10433 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10434 if( rc!=SQLITE_OK ){
10435 return rc;
10436 }
10437 rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
10438 releasePage(pMove);
10439 if( rc!=SQLITE_OK ){
10440 return rc;
10441 }
10442 pMove = 0;
10443 rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
10444 if( rc==SQLITE_OK ){
10445 rc = sqlite3PagerWrite(pMove->pDbPage);
10446 }
10447 freePage(pMove, &rc);
10448 releasePage(pMove);
10449 if( rc!=SQLITE_OK ){
10450 return rc;
10451 }
10452 *piMoved = maxRootPgno;
10453 }
10454
10455 /* Set the new 'max-root-page' value in the database header. This
10456 ** is the old value less one, less one more if that happens to
10457 ** be a root-page number, less one again if that is the
10458 ** PENDING_BYTE_PAGE.
10459 */
10460 maxRootPgno--;
10461 while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
10462 || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
10463 maxRootPgno--;
10464 }
10465 assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
10466
10467 rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
10468 }else{
10469 freePage(pPage, &rc);
10470 releasePage(pPage);
10471 }
10472#endif
10473 return rc;
10474}
10475int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
10476 int rc;
10477 sqlite3BtreeEnter(p);
10478 rc = btreeDropTable(p, iTable, piMoved);
10479 sqlite3BtreeLeave(p);
10480 return rc;
10481}
10482
10483
10484/*
10485** This function may only be called if the b-tree connection already
10486** has a read or write transaction open on the database.
10487**
10488** Read the meta-information out of a database file. Meta[0]
10489** is the number of free pages currently in the database. Meta[1]
10490** through meta[15] are available for use by higher layers. Meta[0]
10491** is read-only, the others are read/write.
10492**
10493** The schema layer numbers meta values differently. At the schema
10494** layer (and the SetCookie and ReadCookie opcodes) the number of
10495** free pages is not visible. So Cookie[0] is the same as Meta[1].
10496**
10497** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
10498** of reading the value out of the header, it instead loads the "DataVersion"
10499** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
10500** database file. It is a number computed by the pager. But its access
10501** pattern is the same as header meta values, and so it is convenient to
10502** read it from this routine.
10503*/
10504void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
10505 BtShared *pBt = p->pBt;
10506
10507 sqlite3BtreeEnter(p);
10508 assert( p->inTrans>TRANS_NONE );
10509 assert( SQLITE_OK==querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK) );
10510 assert( pBt->pPage1 );
10511 assert( idx>=0 && idx<=15 );
10512
10513 if( idx==BTREE_DATA_VERSION ){
10514 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
10515 }else{
10516 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
10517 }
10518
10519 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
10520 ** database, mark the database as read-only. */
10521#ifdef SQLITE_OMIT_AUTOVACUUM
10522 if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
10523 pBt->btsFlags |= BTS_READ_ONLY;
10524 }
10525#endif
10526
10527 sqlite3BtreeLeave(p);
10528}
10529
10530/*
10531** Write meta-information back into the database. Meta[0] is
10532** read-only and may not be written.
10533*/
10534int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
10535 BtShared *pBt = p->pBt;
10536 unsigned char *pP1;
10537 int rc;
10538 assert( idx>=1 && idx<=15 );
10539 sqlite3BtreeEnter(p);
10540 assert( p->inTrans==TRANS_WRITE );
10541 assert( pBt->pPage1!=0 );
10542 pP1 = pBt->pPage1->aData;
10543 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
10544 if( rc==SQLITE_OK ){
10545 put4byte(&pP1[36 + idx*4], iMeta);
10546#ifndef SQLITE_OMIT_AUTOVACUUM
10547 if( idx==BTREE_INCR_VACUUM ){
10548 assert( pBt->autoVacuum || iMeta==0 );
10549 assert( iMeta==0 || iMeta==1 );
10550 pBt->incrVacuum = (u8)iMeta;
10551 }
10552#endif
10553 }
10554 sqlite3BtreeLeave(p);
10555 return rc;
10556}
10557
10558/*
10559** The first argument, pCur, is a cursor opened on some b-tree. Count the
10560** number of entries in the b-tree and write the result to *pnEntry.
10561**
10562** SQLITE_OK is returned if the operation is successfully executed.
10563** Otherwise, if an error is encountered (i.e. an IO error or database
10564** corruption) an SQLite error code is returned.
10565*/
10566int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
10567 i64 nEntry = 0; /* Value to return in *pnEntry */
10568 int rc; /* Return code */
10569
10570 rc = moveToRoot(pCur);
10571 if( rc==SQLITE_EMPTY ){
10572 *pnEntry = 0;
10573 return SQLITE_OK;
10574 }
10575
10576 /* Unless an error occurs, the following loop runs one iteration for each
10577 ** page in the B-Tree structure (not including overflow pages).
10578 */
10579 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
10580 int iIdx; /* Index of child node in parent */
10581 MemPage *pPage; /* Current page of the b-tree */
10582
10583 /* If this is a leaf page or the tree is not an int-key tree, then
10584 ** this page contains countable entries. Increment the entry counter
10585 ** accordingly.
10586 */
10587 pPage = pCur->pPage;
10588 if( pPage->leaf || !pPage->intKey ){
10589 nEntry += pPage->nCell;
10590 }
10591
10592 /* pPage is a leaf node. This loop navigates the cursor so that it
10593 ** points to the first interior cell that it points to the parent of
10594 ** the next page in the tree that has not yet been visited. The
10595 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
10596 ** of the page, or to the number of cells in the page if the next page
10597 ** to visit is the right-child of its parent.
10598 **
10599 ** If all pages in the tree have been visited, return SQLITE_OK to the
10600 ** caller.
10601 */
10602 if( pPage->leaf ){
10603 do {
10604 if( pCur->iPage==0 ){
10605 /* All pages of the b-tree have been visited. Return successfully. */
10606 *pnEntry = nEntry;
10607 return moveToRoot(pCur);
10608 }
10609 moveToParent(pCur);
10610 }while ( pCur->ix>=pCur->pPage->nCell );
10611
10612 pCur->ix++;
10613 pPage = pCur->pPage;
10614 }
10615
10616 /* Descend to the child node of the cell that the cursor currently
10617 ** points at. This is the right-child if (iIdx==pPage->nCell).
10618 */
10619 iIdx = pCur->ix;
10620 if( iIdx==pPage->nCell ){
10621 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
10622 }else{
10623 rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
10624 }
10625 }
10626
10627 /* An error has occurred. Return an error code. */
10628 return rc;
10629}
10630
10631/*
10632** Return the pager associated with a BTree. This routine is used for
10633** testing and debugging only.
10634*/
10635Pager *sqlite3BtreePager(Btree *p){
10636 return p->pBt->pPager;
10637}
10638
10639#ifndef SQLITE_OMIT_INTEGRITY_CHECK
10640/*
10641** Record an OOM error during integrity_check
10642*/
10643static void checkOom(IntegrityCk *pCheck){
10644 pCheck->rc = SQLITE_NOMEM;
10645 pCheck->mxErr = 0; /* Causes integrity_check processing to stop */
10646 if( pCheck->nErr==0 ) pCheck->nErr++;
10647}
10648
10649/*
10650** Invoke the progress handler, if appropriate. Also check for an
10651** interrupt.
10652*/
10653static void checkProgress(IntegrityCk *pCheck){
10654 sqlite3 *db = pCheck->db;
10655 if( AtomicLoad(&db->u1.isInterrupted) ){
10656 pCheck->rc = SQLITE_INTERRUPT;
10657 pCheck->nErr++;
10658 pCheck->mxErr = 0;
10659 }
10660#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10661 if( db->xProgress ){
10662 assert( db->nProgressOps>0 );
10663 pCheck->nStep++;
10664 if( (pCheck->nStep % db->nProgressOps)==0
10665 && db->xProgress(db->pProgressArg)
10666 ){
10667 pCheck->rc = SQLITE_INTERRUPT;
10668 pCheck->nErr++;
10669 pCheck->mxErr = 0;
10670 }
10671 }
10672#endif
10673}
10674
10675/*
10676** Append a message to the error message string.
10677*/
10678static void checkAppendMsg(
10679 IntegrityCk *pCheck,
10680 const char *zFormat,
10681 ...
10682){
10683 va_list ap;
10684 checkProgress(pCheck);
10685 if( !pCheck->mxErr ) return;
10686 pCheck->mxErr--;
10687 pCheck->nErr++;
10688 va_start(ap, zFormat);
10689 if( pCheck->errMsg.nChar ){
10690 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
10691 }
10692 if( pCheck->zPfx ){
10693 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx,
10694 pCheck->v0, pCheck->v1, pCheck->v2);
10695 }
10696 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
10697 va_end(ap);
10698 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
10699 checkOom(pCheck);
10700 }
10701}
10702#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10703
10704#ifndef SQLITE_OMIT_INTEGRITY_CHECK
10705
10706/*
10707** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
10708** corresponds to page iPg is already set.
10709*/
10710static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10711 assert( pCheck->aPgRef!=0 );
10712 assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
10713 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
10714}
10715
10716/*
10717** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
10718*/
10719static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
10720 assert( pCheck->aPgRef!=0 );
10721 assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
10722 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
10723}
10724
10725
10726/*
10727** Add 1 to the reference count for page iPage. If this is the second
10728** reference to the page, add an error message to pCheck->zErrMsg.
10729** Return 1 if there are 2 or more references to the page and 0 if
10730** if this is the first reference to the page.
10731**
10732** Also check that the page number is in bounds.
10733*/
10734static int checkRef(IntegrityCk *pCheck, Pgno iPage){
10735 if( iPage>pCheck->nCkPage || iPage==0 ){
10736 checkAppendMsg(pCheck, "invalid page number %u", iPage);
10737 return 1;
10738 }
10739 if( getPageReferenced(pCheck, iPage) ){
10740 checkAppendMsg(pCheck, "2nd reference to page %u", iPage);
10741 return 1;
10742 }
10743 setPageReferenced(pCheck, iPage);
10744 return 0;
10745}
10746
10747#ifndef SQLITE_OMIT_AUTOVACUUM
10748/*
10749** Check that the entry in the pointer-map for page iChild maps to
10750** page iParent, pointer type ptrType. If not, append an error message
10751** to pCheck.
10752*/
10753static void checkPtrmap(
10754 IntegrityCk *pCheck, /* Integrity check context */
10755 Pgno iChild, /* Child page number */
10756 u8 eType, /* Expected pointer map type */
10757 Pgno iParent /* Expected pointer map parent page number */
10758){
10759 int rc;
10760 u8 ePtrmapType;
10761 Pgno iPtrmapParent;
10762
10763 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
10764 if( rc!=SQLITE_OK ){
10765 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) checkOom(pCheck);
10766 checkAppendMsg(pCheck, "Failed to read ptrmap key=%u", iChild);
10767 return;
10768 }
10769
10770 if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
10771 checkAppendMsg(pCheck,
10772 "Bad ptr map entry key=%u expected=(%u,%u) got=(%u,%u)",
10773 iChild, eType, iParent, ePtrmapType, iPtrmapParent);
10774 }
10775}
10776#endif
10777
10778/*
10779** Check the integrity of the freelist or of an overflow page list.
10780** Verify that the number of pages on the list is N.
10781*/
10782static void checkList(
10783 IntegrityCk *pCheck, /* Integrity checking context */
10784 int isFreeList, /* True for a freelist. False for overflow page list */
10785 Pgno iPage, /* Page number for first page in the list */
10786 u32 N /* Expected number of pages in the list */
10787){
10788 int i;
10789 u32 expected = N;
10790 int nErrAtStart = pCheck->nErr;
10791 while( iPage!=0 && pCheck->mxErr ){
10792 DbPage *pOvflPage;
10793 unsigned char *pOvflData;
10794 if( checkRef(pCheck, iPage) ) break;
10795 N--;
10796 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
10797 checkAppendMsg(pCheck, "failed to get page %u", iPage);
10798 break;
10799 }
10800 pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
10801 if( isFreeList ){
10802 u32 n = (u32)get4byte(&pOvflData[4]);
10803#ifndef SQLITE_OMIT_AUTOVACUUM
10804 if( pCheck->pBt->autoVacuum ){
10805 checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
10806 }
10807#endif
10808 if( n>pCheck->pBt->usableSize/4-2 ){
10809 checkAppendMsg(pCheck,
10810 "freelist leaf count too big on page %u", iPage);
10811 N--;
10812 }else{
10813 for(i=0; i<(int)n; i++){
10814 Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
10815#ifndef SQLITE_OMIT_AUTOVACUUM
10816 if( pCheck->pBt->autoVacuum ){
10817 checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
10818 }
10819#endif
10820 checkRef(pCheck, iFreePage);
10821 }
10822 N -= n;
10823 }
10824 }
10825#ifndef SQLITE_OMIT_AUTOVACUUM
10826 else{
10827 /* If this database supports auto-vacuum and iPage is not the last
10828 ** page in this overflow list, check that the pointer-map entry for
10829 ** the following page matches iPage.
10830 */
10831 if( pCheck->pBt->autoVacuum && N>0 ){
10832 i = get4byte(pOvflData);
10833 checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
10834 }
10835 }
10836#endif
10837 iPage = get4byte(pOvflData);
10838 sqlite3PagerUnref(pOvflPage);
10839 }
10840 if( N && nErrAtStart==pCheck->nErr ){
10841 checkAppendMsg(pCheck,
10842 "%s is %u but should be %u",
10843 isFreeList ? "size" : "overflow list length",
10844 expected-N, expected);
10845 }
10846}
10847#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
10848
10849/*
10850** An implementation of a min-heap.
10851**
10852** aHeap[0] is the number of elements on the heap. aHeap[1] is the
10853** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
10854** and aHeap[N*2+1].
10855**
10856** The heap property is this: Every node is less than or equal to both
10857** of its daughter nodes. A consequence of the heap property is that the
10858** root node aHeap[1] is always the minimum value currently in the heap.
10859**
10860** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
10861** the heap, preserving the heap property. The btreeHeapPull() routine
10862** removes the root element from the heap (the minimum value in the heap)
10863** and then moves other nodes around as necessary to preserve the heap
10864** property.
10865**
10866** This heap is used for cell overlap and coverage testing. Each u32
10867** entry represents the span of a cell or freeblock on a btree page.
10868** The upper 16 bits are the index of the first byte of a range and the
10869** lower 16 bits are the index of the last byte of that range.
10870*/
10871static void btreeHeapInsert(u32 *aHeap, u32 x){
10872 u32 j, i;
10873 assert( aHeap!=0 );
10874 i = ++aHeap[0];
10875 aHeap[i] = x;
10876 while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
10877 x = aHeap[j];
10878 aHeap[j] = aHeap[i];
10879 aHeap[i] = x;
10880 i = j;
10881 }
10882}
10883static int btreeHeapPull(u32 *aHeap, u32 *pOut){
10884 u32 j, i, x;
10885 if( (x = aHeap[0])==0 ) return 0;
10886 *pOut = aHeap[1];
10887 aHeap[1] = aHeap[x];
10888 aHeap[x] = 0xffffffff;
10889 aHeap[0]--;
10890 i = 1;
10891 while( (j = i*2)<=aHeap[0] ){
10892 if( aHeap[j]>aHeap[j+1] ) j++;
10893 if( aHeap[i]<aHeap[j] ) break;
10894 x = aHeap[i];
10895 aHeap[i] = aHeap[j];
10896 aHeap[j] = x;
10897 i = j;
10898 }
10899 return 1;
10900}
10901
10902#ifndef SQLITE_OMIT_INTEGRITY_CHECK
10903/*
10904** Do various sanity checks on a single page of a tree. Return
10905** the tree depth. Root pages return 0. Parents of root pages
10906** return 1, and so forth.
10907**
10908** These checks are done:
10909**
10910** 1. Make sure that cells and freeblocks do not overlap
10911** but combine to completely cover the page.
10912** 2. Make sure integer cell keys are in order.
10913** 3. Check the integrity of overflow pages.
10914** 4. Recursively call checkTreePage on all children.
10915** 5. Verify that the depth of all children is the same.
10916*/
10917static int checkTreePage(
10918 IntegrityCk *pCheck, /* Context for the sanity check */
10919 Pgno iPage, /* Page number of the page to check */
10920 i64 *piMinKey, /* Write minimum integer primary key here */
10921 i64 maxKey /* Error if integer primary key greater than this */
10922){
10923 MemPage *pPage = 0; /* The page being analyzed */
10924 int i; /* Loop counter */
10925 int rc; /* Result code from subroutine call */
10926 int depth = -1, d2; /* Depth of a subtree */
10927 int pgno; /* Page number */
10928 int nFrag; /* Number of fragmented bytes on the page */
10929 int hdr; /* Offset to the page header */
10930 int cellStart; /* Offset to the start of the cell pointer array */
10931 int nCell; /* Number of cells */
10932 int doCoverageCheck = 1; /* True if cell coverage checking should be done */
10933 int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
10934 ** False if IPK must be strictly less than maxKey */
10935 u8 *data; /* Page content */
10936 u8 *pCell; /* Cell content */
10937 u8 *pCellIdx; /* Next element of the cell pointer array */
10938 BtShared *pBt; /* The BtShared object that owns pPage */
10939 u32 pc; /* Address of a cell */
10940 u32 usableSize; /* Usable size of the page */
10941 u32 contentOffset; /* Offset to the start of the cell content area */
10942 u32 *heap = 0; /* Min-heap used for checking cell coverage */
10943 u32 x, prev = 0; /* Next and previous entry on the min-heap */
10944 const char *saved_zPfx = pCheck->zPfx;
10945 int saved_v1 = pCheck->v1;
10946 int saved_v2 = pCheck->v2;
10947 u8 savedIsInit = 0;
10948
10949 /* Check that the page exists
10950 */
10951 checkProgress(pCheck);
10952 if( pCheck->mxErr==0 ) return 0;
10953 pBt = pCheck->pBt;
10954 usableSize = pBt->usableSize;
10955 if( iPage==0 ) return 0;
10956 if( checkRef(pCheck, iPage) ) return 0;
10957 pCheck->zPfx = "Tree %u page %u: ";
10958 pCheck->v1 = iPage;
10959 pCheck->nAbove++;
10960 if( (rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0 ){
10961 checkAppendMsg(pCheck,
10962 "unable to get the page. error code=%d", rc);
10963 if( rc==SQLITE_IOERR_NOMEM ) pCheck->rc = SQLITE_NOMEM;
10964 goto end_of_check;
10965 }
10966 if( pCheck->nAbove > BTCURSOR_MAX_DEPTH ){
10967 checkAppendMsg(pCheck,"btree depth exceeds %d",BTCURSOR_MAX_DEPTH);
10968 goto end_of_check;
10969 }
10970
10971 /* Clear MemPage.isInit to make sure the corruption detection code in
10972 ** btreeInitPage() is executed. */
10973 savedIsInit = pPage->isInit;
10974 pPage->isInit = 0;
10975 if( (rc = btreeInitPage(pPage))!=0 ){
10976 assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
10977 checkAppendMsg(pCheck,
10978 "btreeInitPage() returns error code %d", rc);
10979 goto end_of_check;
10980 }
10981 if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
10982 assert( rc==SQLITE_CORRUPT );
10983 checkAppendMsg(pCheck, "free space corruption", rc);
10984 goto end_of_check;
10985 }
10986 data = pPage->aData;
10987 hdr = pPage->hdrOffset;
10988
10989 /* Set up for cell analysis */
10990 pCheck->zPfx = "Tree %u page %u cell %u: ";
10991 contentOffset = get2byteNotZero(&data[hdr+5]);
10992 assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
10993
10994 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
10995 ** number of cells on the page. */
10996 nCell = get2byte(&data[hdr+3]);
10997 assert( pPage->nCell==nCell );
10998 if( pPage->leaf || pPage->intKey==0 ){
10999 pCheck->nRow += nCell;
11000 }
11001
11002 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
11003 ** immediately follows the b-tree page header. */
11004 cellStart = hdr + 12 - 4*pPage->leaf;
11005 assert( pPage->aCellIdx==&data[cellStart] );
11006 pCellIdx = &data[cellStart + 2*(nCell-1)];
11007
11008 if( !pPage->leaf ){
11009 /* Analyze the right-child page of internal pages */
11010 pgno = get4byte(&data[hdr+8]);
11011#ifndef SQLITE_OMIT_AUTOVACUUM
11012 if( pBt->autoVacuum ){
11013 pCheck->zPfx = "Tree %u page %u right child: ";
11014 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
11015 }
11016#endif
11017 depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
11018 keyCanBeEqual = 0;
11019 }else{
11020 /* For leaf pages, the coverage check will occur in the same loop
11021 ** as the other cell checks, so initialize the heap. */
11022 heap = pCheck->heap;
11023 heap[0] = 0;
11024 }
11025
11026 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
11027 ** integer offsets to the cell contents. */
11028 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
11029 CellInfo info;
11030
11031 /* Check cell size */
11032 pCheck->v2 = i;
11033 assert( pCellIdx==&data[cellStart + i*2] );
11034 pc = get2byteAligned(pCellIdx);
11035 pCellIdx -= 2;
11036 if( pc<contentOffset || pc>usableSize-4 ){
11037 checkAppendMsg(pCheck, "Offset %u out of range %u..%u",
11038 pc, contentOffset, usableSize-4);
11039 doCoverageCheck = 0;
11040 continue;
11041 }
11042 pCell = &data[pc];
11043 pPage->xParseCell(pPage, pCell, &info);
11044 if( pc+info.nSize>usableSize ){
11045 checkAppendMsg(pCheck, "Extends off end of page");
11046 doCoverageCheck = 0;
11047 continue;
11048 }
11049 if( info.nPayload && info.pPayload[0]<2 ){
11050 checkAppendMsg(pCheck, "Bad cell header size");
11051 doCoverageCheck = 0;
11052 continue;
11053 }
11054
11055 /* Check for integer primary key out of range */
11056 if( pPage->intKey ){
11057 if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
11058 checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
11059 }
11060 maxKey = info.nKey;
11061 keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
11062 }
11063
11064 /* Check the content overflow list */
11065 if( info.nPayload>info.nLocal ){
11066 u32 nPage; /* Number of pages on the overflow chain */
11067 Pgno pgnoOvfl; /* First page of the overflow chain */
11068 assert( pc + info.nSize - 4 <= usableSize );
11069 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
11070 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
11071#ifndef SQLITE_OMIT_AUTOVACUUM
11072 if( pBt->autoVacuum ){
11073 checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
11074 }
11075#endif
11076 checkList(pCheck, 0, pgnoOvfl, nPage);
11077 }
11078
11079 if( !pPage->leaf ){
11080 /* Check sanity of left child page for internal pages */
11081 pgno = get4byte(pCell);
11082#ifndef SQLITE_OMIT_AUTOVACUUM
11083 if( pBt->autoVacuum ){
11084 checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
11085 }
11086#endif
11087 d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
11088 keyCanBeEqual = 0;
11089 if( d2!=depth ){
11090 checkAppendMsg(pCheck, "Child page depth differs");
11091 depth = d2;
11092 }
11093 }else{
11094 /* Populate the coverage-checking heap for leaf pages */
11095 assert( heap!=0 && heap[0] < pCheck->mxHeap );
11096 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
11097 }
11098 }
11099 *piMinKey = maxKey;
11100
11101 /* Check for complete coverage of the page
11102 */
11103 pCheck->zPfx = 0;
11104 if( doCoverageCheck && pCheck->mxErr>0 ){
11105 /* For leaf pages, the min-heap has already been initialized and the
11106 ** cells have already been inserted. But for internal pages, that has
11107 ** not yet been done, so do it now */
11108 if( !pPage->leaf ){
11109 heap = pCheck->heap;
11110 heap[0] = 0;
11111 for(i=nCell-1; i>=0; i--){
11112 u32 size;
11113 pc = get2byteAligned(&data[cellStart+i*2]);
11114 size = pPage->xCellSize(pPage, &data[pc]);
11115 assert( heap!=0 && heap[0] < pCheck->mxHeap );
11116 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
11117 }
11118 }
11119 assert( heap!=0 );
11120 /* Add the freeblocks to the min-heap
11121 **
11122 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
11123 ** is the offset of the first freeblock, or zero if there are no
11124 ** freeblocks on the page.
11125 */
11126 i = get2byte(&data[hdr+1]);
11127 while( i>0 ){
11128 int size, j;
11129 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
11130 size = get2byte(&data[i+2]);
11131 assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
11132 assert( heap!=0 && heap[0] < pCheck->mxHeap );
11133 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
11134 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
11135 ** big-endian integer which is the offset in the b-tree page of the next
11136 ** freeblock in the chain, or zero if the freeblock is the last on the
11137 ** chain. */
11138 j = get2byte(&data[i]);
11139 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
11140 ** increasing offset. */
11141 assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
11142 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
11143 i = j;
11144 }
11145 /* Analyze the min-heap looking for overlap between cells and/or
11146 ** freeblocks, and counting the number of untracked bytes in nFrag.
11147 **
11148 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
11149 ** There is an implied first entry the covers the page header, the cell
11150 ** pointer index, and the gap between the cell pointer index and the start
11151 ** of cell content.
11152 **
11153 ** The loop below pulls entries from the min-heap in order and compares
11154 ** the start_address against the previous end_address. If there is an
11155 ** overlap, that means bytes are used multiple times. If there is a gap,
11156 ** that gap is added to the fragmentation count.
11157 */
11158 nFrag = 0;
11159 prev = contentOffset - 1; /* Implied first min-heap entry */
11160 while( btreeHeapPull(heap,&x) ){
11161 if( (prev&0xffff)>=(x>>16) ){
11162 checkAppendMsg(pCheck,
11163 "Multiple uses for byte %u of page %u", x>>16, iPage);
11164 break;
11165 }else{
11166 nFrag += (x>>16) - (prev&0xffff) - 1;
11167 prev = x;
11168 }
11169 }
11170 nFrag += usableSize - (prev&0xffff) - 1;
11171 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
11172 ** is stored in the fifth field of the b-tree page header.
11173 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
11174 ** number of fragmented free bytes within the cell content area.
11175 */
11176 if( heap[0]==0 && nFrag!=data[hdr+7] ){
11177 checkAppendMsg(pCheck,
11178 "Fragmentation of %u bytes reported as %u on page %u",
11179 nFrag, data[hdr+7], iPage);
11180 }
11181 }
11182
11183end_of_check:
11184 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
11185 releasePage(pPage);
11186 pCheck->zPfx = saved_zPfx;
11187 pCheck->v1 = saved_v1;
11188 pCheck->v2 = saved_v2;
11189 pCheck->nAbove--;
11190 return depth+1;
11191}
11192#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
11193
11194#ifndef SQLITE_OMIT_INTEGRITY_CHECK
11195/*
11196** This routine does a complete check of the given BTree file. aRoot[] is
11197** an array of pages numbers were each page number is the root page of
11198** a table. nRoot is the number of entries in aRoot.
11199**
11200** A read-only or read-write transaction must be opened before calling
11201** this function.
11202**
11203** Write the number of error seen in *pnErr. Except for some memory
11204** allocation errors, an error message held in memory obtained from
11205** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
11206** returned. If a memory allocation error occurs, NULL is returned.
11207**
11208** If the first entry in aRoot[] is 0, that indicates that the list of
11209** root pages is incomplete. This is a "partial integrity-check". This
11210** happens when performing an integrity check on a single table. The
11211** zero is skipped, of course. But in addition, the freelist checks
11212** and the checks to make sure every page is referenced are also skipped,
11213** since obviously it is not possible to know which pages are covered by
11214** the unverified btrees. Except, if aRoot[1] is 1, then the freelist
11215** checks are still performed.
11216*/
11217int sqlite3BtreeIntegrityCheck(
11218 sqlite3 *db, /* Database connection that is running the check */
11219 Btree *p, /* The btree to be checked */
11220 Pgno *aRoot, /* An array of root pages numbers for individual trees */
11221 Mem *aCnt, /* Memory cells to write counts for each tree to */
11222 int nRoot, /* Number of entries in aRoot[] */
11223 int mxErr, /* Stop reporting errors after this many */
11224 int *pnErr, /* OUT: Write number of errors seen to this variable */
11225 char **pzOut /* OUT: Write the error message string here */
11226){
11227 Pgno i;
11228 IntegrityCk sCheck;
11229 BtShared *pBt = p->pBt;
11230 u64 savedDbFlags = pBt->db->flags;
11231 char zErr[100];
11232 int bPartial = 0; /* True if not checking all btrees */
11233 int bCkFreelist = 1; /* True to scan the freelist */
11234 VVA_ONLY( int nRef );
11235
11236 assert( nRoot>0 );
11237 assert( aCnt!=0 );
11238
11239 /* aRoot[0]==0 means this is a partial check */
11240 if( aRoot[0]==0 ){
11241 assert( nRoot>1 );
11242 bPartial = 1;
11243 if( aRoot[1]!=1 ) bCkFreelist = 0;
11244 }
11245
11246 sqlite3BtreeEnter(p);
11247 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
11248 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
11249 assert( nRef>=0 );
11250 memset(&sCheck, 0, sizeof(sCheck));
11251 sCheck.db = db;
11252 sCheck.pBt = pBt;
11253 sCheck.pPager = pBt->pPager;
11254 sCheck.nCkPage = btreePagecount(sCheck.pBt);
11255 sCheck.mxErr = mxErr;
11256 sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
11257 sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
11258 if( sCheck.nCkPage==0 ){
11259 goto integrity_ck_cleanup;
11260 }
11261
11262 sCheck.aPgRef = sqlite3MallocZero((sCheck.nCkPage / 8)+ 1);
11263 if( !sCheck.aPgRef ){
11264 checkOom(&sCheck);
11265 goto integrity_ck_cleanup;
11266 }
11267 sCheck.heap = (u32*)sqlite3Malloc( pBt->pageSize*2 );
11268#ifdef SQLITE_DEBUG
11269 sCheck.mxHeap = pBt->pageSize/2 - 1;
11270#endif
11271 if( sCheck.heap==0 ){
11272 checkOom(&sCheck);
11273 goto integrity_ck_cleanup;
11274 }
11275
11276 i = PENDING_BYTE_PAGE(pBt);
11277 if( i<=sCheck.nCkPage ) setPageReferenced(&sCheck, i);
11278
11279 /* Check the integrity of the freelist
11280 */
11281 if( bCkFreelist ){
11282 sCheck.zPfx = "Freelist: ";
11283 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
11284 get4byte(&pBt->pPage1->aData[36]));
11285 sCheck.zPfx = 0;
11286 }
11287
11288 /* Check all the tables.
11289 */
11290#ifndef SQLITE_OMIT_AUTOVACUUM
11291 if( !bPartial ){
11292 if( pBt->autoVacuum ){
11293 Pgno mx = 0;
11294 Pgno mxInHdr;
11295 for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
11296 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
11297 if( mx!=mxInHdr ){
11298 checkAppendMsg(&sCheck,
11299 "max rootpage (%u) disagrees with header (%u)",
11300 mx, mxInHdr
11301 );
11302 }
11303 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
11304 checkAppendMsg(&sCheck,
11305 "incremental_vacuum enabled with a max rootpage of zero"
11306 );
11307 }
11308 }
11309#endif
11310 testcase( pBt->db->flags & SQLITE_CellSizeCk );
11311 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
11312 for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
11313 sCheck.nRow = 0;
11314 if( aRoot[i] ){
11315 i64 notUsed;
11316#ifndef SQLITE_OMIT_AUTOVACUUM
11317 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
11318 checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
11319 }
11320#endif
11321 sCheck.v0 = aRoot[i];
11322 assert( sCheck.nAbove==0 );
11323 checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
11324 assert( sCheck.nAbove==0 );
11325 }
11326 sqlite3MemSetArrayInt64(aCnt, i, sCheck.nRow);
11327 }
11328 pBt->db->flags = savedDbFlags;
11329
11330 /* Make sure every page in the file is referenced
11331 */
11332 if( !bPartial ){
11333 for(i=1; i<=sCheck.nCkPage && sCheck.mxErr; i++){
11334#ifdef SQLITE_OMIT_AUTOVACUUM
11335 if( getPageReferenced(&sCheck, i)==0 ){
11336 checkAppendMsg(&sCheck, "Page %u: never used", i);
11337 }
11338#else
11339 /* If the database supports auto-vacuum, make sure no tables contain
11340 ** references to pointer-map pages.
11341 */
11342 if( getPageReferenced(&sCheck, i)==0 &&
11343 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
11344 checkAppendMsg(&sCheck, "Page %u: never used", i);
11345 }
11346 if( getPageReferenced(&sCheck, i)!=0 &&
11347 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
11348 checkAppendMsg(&sCheck, "Page %u: pointer map referenced", i);
11349 }
11350#endif
11351 }
11352 }
11353
11354 /* Clean up and report errors.
11355 */
11356integrity_ck_cleanup:
11357 sqlite3_free(sCheck.heap);
11358 sqlite3_free(sCheck.aPgRef);
11359 *pnErr = sCheck.nErr;
11360 if( sCheck.nErr==0 ){
11361 sqlite3_str_reset(&sCheck.errMsg);
11362 *pzOut = 0;
11363 }else{
11364 *pzOut = sqlite3StrAccumFinish(&sCheck.errMsg);
11365 }
11366 /* Make sure this analysis did not leave any unref() pages. */
11367 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
11368 sqlite3BtreeLeave(p);
11369 return sCheck.rc;
11370}
11371#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
11372
11373/*
11374** Return the full pathname of the underlying database file. Return
11375** an empty string if the database is in-memory or a TEMP database.
11376**
11377** The pager filename is invariant as long as the pager is
11378** open so it is safe to access without the BtShared mutex.
11379*/
11380const char *sqlite3BtreeGetFilename(Btree *p){
11381 assert( p->pBt->pPager!=0 );
11382 return sqlite3PagerFilename(p->pBt->pPager, 1);
11383}
11384
11385/*
11386** Return the pathname of the journal file for this database. The return
11387** value of this routine is the same regardless of whether the journal file
11388** has been created or not.
11389**
11390** The pager journal filename is invariant as long as the pager is
11391** open so it is safe to access without the BtShared mutex.
11392*/
11393const char *sqlite3BtreeGetJournalname(Btree *p){
11394 assert( p->pBt->pPager!=0 );
11395 return sqlite3PagerJournalname(p->pBt->pPager);
11396}
11397
11398/*
11399** Return one of SQLITE_TXN_NONE, SQLITE_TXN_READ, or SQLITE_TXN_WRITE
11400** to describe the current transaction state of Btree p.
11401*/
11402int sqlite3BtreeTxnState(Btree *p){
11403 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
11404 return p ? p->inTrans : 0;
11405}
11406
11407#ifndef SQLITE_OMIT_WAL
11408/*
11409** Run a checkpoint on the Btree passed as the first argument.
11410**
11411** Return SQLITE_LOCKED if this or any other connection has an open
11412** transaction on the shared-cache the argument Btree is connected to.
11413**
11414** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
11415*/
11416int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
11417 int rc = SQLITE_OK;
11418 if( p ){
11419 BtShared *pBt = p->pBt;
11420 sqlite3BtreeEnter(p);
11421 if( pBt->inTransaction!=TRANS_NONE ){
11422 rc = SQLITE_LOCKED;
11423 }else{
11424 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
11425 }
11426 sqlite3BtreeLeave(p);
11427 }
11428 return rc;
11429}
11430#endif
11431
11432/*
11433** Return true if there is currently a backup running on Btree p.
11434*/
11435int sqlite3BtreeIsInBackup(Btree *p){
11436 assert( p );
11437 assert( sqlite3_mutex_held(p->db->mutex) );
11438 return p->nBackup!=0;
11439}
11440
11441/*
11442** This function returns a pointer to a blob of memory associated with
11443** a single shared-btree. The memory is used by client code for its own
11444** purposes (for example, to store a high-level schema associated with
11445** the shared-btree). The btree layer manages reference counting issues.
11446**
11447** The first time this is called on a shared-btree, nBytes bytes of memory
11448** are allocated, zeroed, and returned to the caller. For each subsequent
11449** call the nBytes parameter is ignored and a pointer to the same blob
11450** of memory returned.
11451**
11452** If the nBytes parameter is 0 and the blob of memory has not yet been
11453** allocated, a null pointer is returned. If the blob has already been
11454** allocated, it is returned as normal.
11455**
11456** Just before the shared-btree is closed, the function passed as the
11457** xFree argument when the memory allocation was made is invoked on the
11458** blob of allocated memory. The xFree function should not call sqlite3_free()
11459** on the memory, the btree layer does that.
11460*/
11461void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
11462 BtShared *pBt = p->pBt;
11463 assert( nBytes==0 || nBytes==sizeof(Schema) );
11464 sqlite3BtreeEnter(p);
11465 if( !pBt->pSchema && nBytes ){
11466 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
11467 pBt->xFreeSchema = xFree;
11468 }
11469 sqlite3BtreeLeave(p);
11470 return pBt->pSchema;
11471}
11472
11473/*
11474** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
11475** btree as the argument handle holds an exclusive lock on the
11476** sqlite_schema table. Otherwise SQLITE_OK.
11477*/
11478int sqlite3BtreeSchemaLocked(Btree *p){
11479 int rc;
11480 UNUSED_PARAMETER(p); /* only used in DEBUG builds */
11481 assert( sqlite3_mutex_held(p->db->mutex) );
11482 sqlite3BtreeEnter(p);
11483 rc = querySharedCacheTableLock(p, SCHEMA_ROOT, READ_LOCK);
11484 assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
11485 sqlite3BtreeLeave(p);
11486 return rc;
11487}
11488
11489
11490#ifndef SQLITE_OMIT_SHARED_CACHE
11491/*
11492** Obtain a lock on the table whose root page is iTab. The
11493** lock is a write lock if isWritelock is true or a read lock
11494** if it is false.
11495*/
11496int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
11497 int rc = SQLITE_OK;
11498 assert( p->inTrans!=TRANS_NONE );
11499 if( p->sharable ){
11500 u8 lockType = READ_LOCK + isWriteLock;
11501 assert( READ_LOCK+1==WRITE_LOCK );
11502 assert( isWriteLock==0 || isWriteLock==1 );
11503
11504 sqlite3BtreeEnter(p);
11505 rc = querySharedCacheTableLock(p, iTab, lockType);
11506 if( rc==SQLITE_OK ){
11507 rc = setSharedCacheTableLock(p, iTab, lockType);
11508 }
11509 sqlite3BtreeLeave(p);
11510 }
11511 return rc;
11512}
11513#endif
11514
11515#ifndef SQLITE_OMIT_INCRBLOB
11516/*
11517** Argument pCsr must be a cursor opened for writing on an
11518** INTKEY table currently pointing at a valid table entry.
11519** This function modifies the data stored as part of that entry.
11520**
11521** Only the data content may only be modified, it is not possible to
11522** change the length of the data stored. If this function is called with
11523** parameters that attempt to write past the end of the existing data,
11524** no modifications are made and SQLITE_CORRUPT is returned.
11525*/
11526int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
11527 int rc;
11528 assert( cursorOwnsBtShared(pCsr) );
11529 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
11530 assert( pCsr->curFlags & BTCF_Incrblob );
11531
11532 rc = restoreCursorPosition(pCsr);
11533 if( rc!=SQLITE_OK ){
11534 return rc;
11535 }
11536 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
11537 if( pCsr->eState!=CURSOR_VALID ){
11538 return SQLITE_ABORT;
11539 }
11540
11541 /* Save the positions of all other cursors open on this table. This is
11542 ** required in case any of them are holding references to an xFetch
11543 ** version of the b-tree page modified by the accessPayload call below.
11544 **
11545 ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
11546 ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
11547 ** saveAllCursors can only return SQLITE_OK.
11548 */
11549 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
11550 assert( rc==SQLITE_OK );
11551
11552 /* Check some assumptions:
11553 ** (a) the cursor is open for writing,
11554 ** (b) there is a read/write transaction open,
11555 ** (c) the connection holds a write-lock on the table (if required),
11556 ** (d) there are no conflicting read-locks, and
11557 ** (e) the cursor points at a valid row of an intKey table.
11558 */
11559 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
11560 return SQLITE_READONLY;
11561 }
11562 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
11563 && pCsr->pBt->inTransaction==TRANS_WRITE );
11564 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
11565 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
11566 assert( pCsr->pPage->intKey );
11567
11568 return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
11569}
11570
11571/*
11572** Mark this cursor as an incremental blob cursor.
11573*/
11574void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
11575 pCur->curFlags |= BTCF_Incrblob;
11576 pCur->pBtree->hasIncrblobCur = 1;
11577}
11578#endif
11579
11580/*
11581** Set both the "read version" (single byte at byte offset 18) and
11582** "write version" (single byte at byte offset 19) fields in the database
11583** header to iVersion.
11584*/
11585int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
11586 BtShared *pBt = pBtree->pBt;
11587 int rc; /* Return code */
11588
11589 assert( iVersion==1 || iVersion==2 );
11590
11591 /* If setting the version fields to 1, do not automatically open the
11592 ** WAL connection, even if the version fields are currently set to 2.
11593 */
11594 pBt->btsFlags &= ~BTS_NO_WAL;
11595 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
11596
11597 rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
11598 if( rc==SQLITE_OK ){
11599 u8 *aData = pBt->pPage1->aData;
11600 if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
11601 rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
11602 if( rc==SQLITE_OK ){
11603 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
11604 if( rc==SQLITE_OK ){
11605 aData[18] = (u8)iVersion;
11606 aData[19] = (u8)iVersion;
11607 }
11608 }
11609 }
11610 }
11611
11612 pBt->btsFlags &= ~BTS_NO_WAL;
11613 return rc;
11614}
11615
11616/*
11617** Return true if the cursor has a hint specified. This routine is
11618** only used from within assert() statements
11619*/
11620int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
11621 return (pCsr->hints & mask)!=0;
11622}
11623
11624/*
11625** Return true if the given Btree is read-only.
11626*/
11627int sqlite3BtreeIsReadonly(Btree *p){
11628 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
11629}
11630
11631/*
11632** Return the size of the header added to each page by this module.
11633*/
11634int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
11635
11636/*
11637** If no transaction is active and the database is not a temp-db, clear
11638** the in-memory pager cache.
11639*/
11640void sqlite3BtreeClearCache(Btree *p){
11641 BtShared *pBt = p->pBt;
11642 if( pBt->inTransaction==TRANS_NONE ){
11643 sqlite3PagerClearCache(pBt->pPager);
11644 }
11645}
11646
11647#if !defined(SQLITE_OMIT_SHARED_CACHE)
11648/*
11649** Return true if the Btree passed as the only argument is sharable.
11650*/
11651int sqlite3BtreeSharable(Btree *p){
11652 return p->sharable;
11653}
11654
11655/*
11656** Return the number of connections to the BtShared object accessed by
11657** the Btree handle passed as the only argument. For private caches
11658** this is always 1. For shared caches it may be 1 or greater.
11659*/
11660int sqlite3BtreeConnectionCount(Btree *p){
11661 testcase( p->sharable );
11662 return p->pBt->nRef;
11663}
11664#endif
11665
11666/* Re-enable GCC compiler warnings that were suppressed at the top
11667** of this source file to prevent annoying false-positives.
11668*/
11669#if defined(__GNUC__) && __GNUC__>=11
11670# pragma GCC diagnostic pop
11671#endif