~ubuntu-branches/ubuntu/wily/sqlite3/wily

« back to all changes in this revision

Viewing changes to src/btree.c

  • Committer: Package Import Robot
  • Author(s): Colin Watson
  • Date: 2011-09-27 00:09:20 UTC
  • mfrom: (0.23.1) (1.6.1) (16.3.5 oneiric)
  • Revision ID: package-import@ubuntu.com-20110927000920-8d87xm2c8837llx3
Tags: 3.7.7-2ubuntu2
Make sure to build lemon when cross-compiling.

Show diffs side-by-side

added added

removed removed

Lines of Context:
32
32
# define TRACE(X)
33
33
#endif
34
34
 
35
 
 
 
35
/*
 
36
** Extract a 2-byte big-endian integer from an array of unsigned bytes.
 
37
** But if the value is zero, make it 65536.
 
38
**
 
39
** This routine is used to extract the "offset to cell content area" value
 
40
** from the header of a btree page.  If the page size is 65536 and the page
 
41
** is empty, the offset should be 65536, but the 2-byte value stores zero.
 
42
** This routine makes the necessary adjustment to 65536.
 
43
*/
 
44
#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
36
45
 
37
46
#ifndef SQLITE_OMIT_SHARED_CACHE
38
47
/*
516
525
static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
517
526
  int rc = SQLITE_OK;
518
527
  if( !pBt->pHasContent ){
519
 
    int nPage = 100;
520
 
    sqlite3PagerPagecount(pBt->pPager, &nPage);
521
 
    /* If sqlite3PagerPagecount() fails there is no harm because the
522
 
    ** nPage variable is unchanged from its default value of 100 */
523
 
    pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
 
528
    assert( pgno<=pBt->nPage );
 
529
    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
524
530
    if( !pBt->pHasContent ){
525
531
      rc = SQLITE_NOMEM;
526
532
    }
724
730
** Given a page number of a regular database page, return the page
725
731
** number for the pointer-map page that contains the entry for the
726
732
** input page number.
 
733
**
 
734
** Return 0 (not a valid page) for pgno==1 since there is
 
735
** no pointer map associated with page 1.  The integrity_check logic
 
736
** requires that ptrmapPageno(*,1)!=1.
727
737
*/
728
738
static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
729
739
  int nPagesPerMapPage;
730
740
  Pgno iPtrMap, ret;
731
741
  assert( sqlite3_mutex_held(pBt->mutex) );
 
742
  if( pgno<2 ) return 0;
732
743
  nPagesPerMapPage = (pBt->usableSize/5)+1;
733
744
  iPtrMap = (pgno-2)/nPagesPerMapPage;
734
745
  ret = (iPtrMap*nPagesPerMapPage) + 2; 
777
788
    *pRC = SQLITE_CORRUPT_BKPT;
778
789
    goto ptrmap_exit;
779
790
  }
 
791
  assert( offset <= (int)pBt->usableSize-5 );
780
792
  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
781
793
 
782
794
  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
816
828
  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
817
829
 
818
830
  offset = PTRMAP_PTROFFSET(iPtrmap, key);
 
831
  if( offset<0 ){
 
832
    sqlite3PagerUnref(pDbPage);
 
833
    return SQLITE_CORRUPT_BKPT;
 
834
  }
 
835
  assert( offset <= (int)pBt->usableSize-5 );
819
836
  assert( pEType!=0 );
820
837
  *pEType = pPtrmap[offset];
821
838
  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
840
857
*/
841
858
#define findCell(P,I) \
842
859
  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
 
860
#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
 
861
 
843
862
 
844
863
/*
845
864
** This a more complex version of findCell() that works for
907
926
    /* This is the (easy) common case where the entire payload fits
908
927
    ** on the local page.  No overflow is required.
909
928
    */
910
 
    int nSize;          /* Total size of cell content in bytes */
911
 
    nSize = nPayload + n;
 
929
    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
912
930
    pInfo->nLocal = (u16)nPayload;
913
931
    pInfo->iOverflow = 0;
914
 
    if( (nSize & ~3)==0 ){
915
 
      nSize = 4;        /* Minimum cell size is 4 */
916
 
    }
917
 
    pInfo->nSize = (u16)nSize;
918
932
  }else{
919
933
    /* If the payload will not fit completely on the local page, we have
920
934
    ** to decide how much to store locally and how much to spill onto
1157
1171
  nFrag = data[hdr+7];
1158
1172
  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
1159
1173
  gap = pPage->cellOffset + 2*pPage->nCell;
1160
 
  top = get2byte(&data[hdr+5]);
 
1174
  top = get2byteNotZero(&data[hdr+5]);
1161
1175
  if( gap>top ) return SQLITE_CORRUPT_BKPT;
1162
1176
  testcase( gap+2==top );
1163
1177
  testcase( gap+1==top );
1167
1181
    /* Always defragment highly fragmented pages */
1168
1182
    rc = defragmentPage(pPage);
1169
1183
    if( rc ) return rc;
1170
 
    top = get2byte(&data[hdr+5]);
 
1184
    top = get2byteNotZero(&data[hdr+5]);
1171
1185
  }else if( gap+2<=top ){
1172
1186
    /* Search the freelist looking for a free slot big enough to satisfy 
1173
1187
    ** the request. The allocation is made from the first free slot in 
1209
1223
  if( gap+2+nByte>top ){
1210
1224
    rc = defragmentPage(pPage);
1211
1225
    if( rc ) return rc;
1212
 
    top = get2byte(&data[hdr+5]);
 
1226
    top = get2byteNotZero(&data[hdr+5]);
1213
1227
    assert( gap+nByte<=top );
1214
1228
  }
1215
1229
 
1222
1236
  */
1223
1237
  top -= nByte;
1224
1238
  put2byte(&data[hdr+5], top);
1225
 
  assert( top+nByte <= pPage->pBt->usableSize );
 
1239
  assert( top+nByte <= (int)pPage->pBt->usableSize );
1226
1240
  *pIdx = top;
1227
1241
  return SQLITE_OK;
1228
1242
}
1243
1257
  assert( pPage->pBt!=0 );
1244
1258
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1245
1259
  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
1246
 
  assert( (start + size)<=pPage->pBt->usableSize );
 
1260
  assert( (start + size) <= (int)pPage->pBt->usableSize );
1247
1261
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
1248
1262
  assert( size>=0 );   /* Minimum cell size is 4 */
1249
1263
 
1250
 
#ifdef SQLITE_SECURE_DELETE
1251
 
  /* Overwrite deleted information with zeros when the SECURE_DELETE 
1252
 
  ** option is enabled at compile-time */
1253
 
  memset(&data[start], 0, size);
1254
 
#endif
 
1264
  if( pPage->pBt->secureDelete ){
 
1265
    /* Overwrite deleted information with zeros when the secure_delete
 
1266
    ** option is enabled */
 
1267
    memset(&data[start], 0, size);
 
1268
  }
1255
1269
 
1256
1270
  /* Add the space back into the linked list of freeblocks.  Note that
1257
1271
  ** even though the freeblock list was checked by btreeInitPage(),
1286
1300
  while( (pbegin = get2byte(&data[addr]))>0 ){
1287
1301
    int pnext, psize, x;
1288
1302
    assert( pbegin>addr );
1289
 
    assert( pbegin<=pPage->pBt->usableSize-4 );
 
1303
    assert( pbegin <= (int)pPage->pBt->usableSize-4 );
1290
1304
    pnext = get2byte(&data[pbegin]);
1291
1305
    psize = get2byte(&data[pbegin+2]);
1292
1306
    if( pbegin + psize + 3 >= pnext && pnext>0 ){
1375
1389
    u8 hdr;            /* Offset to beginning of page header */
1376
1390
    u8 *data;          /* Equal to pPage->aData */
1377
1391
    BtShared *pBt;        /* The main btree structure */
1378
 
    u16 usableSize;    /* Amount of usable space on each page */
 
1392
    int usableSize;    /* Amount of usable space on each page */
1379
1393
    u16 cellOffset;    /* Offset from start of page to first cell pointer */
1380
 
    u16 nFree;         /* Number of unused bytes on the page */
1381
 
    u16 top;           /* First byte of the cell content area */
 
1394
    int nFree;         /* Number of unused bytes on the page */
 
1395
    int top;           /* First byte of the cell content area */
1382
1396
    int iCellFirst;    /* First allowable cell or freeblock offset */
1383
1397
    int iCellLast;     /* Last possible cell or freeblock offset */
1384
1398
 
1387
1401
    hdr = pPage->hdrOffset;
1388
1402
    data = pPage->aData;
1389
1403
    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
1390
 
    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1391
 
    pPage->maskPage = pBt->pageSize - 1;
 
1404
    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 
1405
    pPage->maskPage = (u16)(pBt->pageSize - 1);
1392
1406
    pPage->nOverflow = 0;
1393
1407
    usableSize = pBt->usableSize;
1394
1408
    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
1395
 
    top = get2byte(&data[hdr+5]);
 
1409
    top = get2byteNotZero(&data[hdr+5]);
1396
1410
    pPage->nCell = get2byte(&data[hdr+3]);
1397
1411
    if( pPage->nCell>MX_CELL(pBt) ){
1398
1412
      /* To many cells for a single page.  The page must be corrupt */
1483
1497
  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
1484
1498
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
1485
1499
  assert( sqlite3_mutex_held(pBt->mutex) );
1486
 
#ifdef SQLITE_SECURE_DELETE
1487
 
  memset(&data[hdr], 0, pBt->usableSize - hdr);
1488
 
#endif
 
1500
  if( pBt->secureDelete ){
 
1501
    memset(&data[hdr], 0, pBt->usableSize - hdr);
 
1502
  }
1489
1503
  data[hdr] = (char)flags;
1490
1504
  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
1491
1505
  memset(&data[hdr+1], 0, 4);
1492
1506
  data[hdr+7] = 0;
1493
1507
  put2byte(&data[hdr+5], pBt->usableSize);
1494
 
  pPage->nFree = pBt->usableSize - first;
 
1508
  pPage->nFree = (u16)(pBt->usableSize - first);
1495
1509
  decodeFlags(pPage, flags);
1496
1510
  pPage->hdrOffset = hdr;
1497
1511
  pPage->cellOffset = first;
1498
1512
  pPage->nOverflow = 0;
1499
 
  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
1500
 
  pPage->maskPage = pBt->pageSize - 1;
 
1513
  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
 
1514
  pPage->maskPage = (u16)(pBt->pageSize - 1);
1501
1515
  pPage->nCell = 0;
1502
1516
  pPage->isInit = 1;
1503
1517
}
1563
1577
** Return the size of the database file in pages. If there is any kind of
1564
1578
** error, return ((unsigned int)-1).
1565
1579
*/
1566
 
static Pgno pagerPagecount(BtShared *pBt){
1567
 
  int nPage = -1;
1568
 
  int rc;
1569
 
  assert( pBt->pPage1 );
1570
 
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
1571
 
  assert( rc==SQLITE_OK || nPage==-1 );
1572
 
  return (Pgno)nPage;
 
1580
static Pgno btreePagecount(BtShared *pBt){
 
1581
  return pBt->nPage;
 
1582
}
 
1583
u32 sqlite3BtreeLastPage(Btree *p){
 
1584
  assert( sqlite3BtreeHoldsMutex(p) );
 
1585
  assert( ((p->pBt->nPage)&0x8000000)==0 );
 
1586
  return (int)btreePagecount(p->pBt);
1573
1587
}
1574
1588
 
1575
1589
/*
1586
1600
  MemPage **ppPage     /* Write the page pointer here */
1587
1601
){
1588
1602
  int rc;
1589
 
  TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
1590
1603
  assert( sqlite3_mutex_held(pBt->mutex) );
1591
1604
 
1592
 
  rc = btreeGetPage(pBt, pgno, ppPage, 0);
1593
 
  if( rc==SQLITE_OK ){
1594
 
    rc = btreeInitPage(*ppPage);
1595
 
    if( rc!=SQLITE_OK ){
1596
 
      releasePage(*ppPage);
 
1605
  if( pgno>btreePagecount(pBt) ){
 
1606
    rc = SQLITE_CORRUPT_BKPT;
 
1607
  }else{
 
1608
    rc = btreeGetPage(pBt, pgno, ppPage, 0);
 
1609
    if( rc==SQLITE_OK ){
 
1610
      rc = btreeInitPage(*ppPage);
 
1611
      if( rc!=SQLITE_OK ){
 
1612
        releasePage(*ppPage);
 
1613
      }
1597
1614
    }
1598
1615
  }
1599
1616
 
1600
 
  /* If the requested page number was either 0 or greater than the page
1601
 
  ** number of the last page in the database, this function should return
1602
 
  ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
1603
 
  ** is the case.  */
1604
 
  assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
1605
1617
  testcase( pgno==0 );
1606
 
  testcase( pgno==iLastPg );
1607
 
 
 
1618
  assert( pgno!=0 || rc==SQLITE_CORRUPT );
1608
1619
  return rc;
1609
1620
}
1610
1621
 
1664
1675
** Open a database file.
1665
1676
** 
1666
1677
** zFilename is the name of the database file.  If zFilename is NULL
1667
 
** a new database with a random name is created.  This randomly named
1668
 
** database file will be deleted when sqlite3BtreeClose() is called.
 
1678
** then an ephemeral database is created.  The ephemeral database might
 
1679
** be exclusively in memory, or it might use a disk-based memory cache.
 
1680
** Either way, the ephemeral database will be automatically deleted 
 
1681
** when sqlite3BtreeClose() is called.
 
1682
**
1669
1683
** If zFilename is ":memory:" then an in-memory database is created
1670
1684
** that is automatically destroyed when it is closed.
1671
1685
**
 
1686
** The "flags" parameter is a bitmask that might contain bits
 
1687
** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
 
1688
** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
 
1689
** These flags are passed through into sqlite3PagerOpen() and must
 
1690
** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
 
1691
**
1672
1692
** If the database is already opened in the same database connection
1673
1693
** and we are in shared cache mode, then the open will fail with an
1674
1694
** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
1676
1696
** to problems with locking.
1677
1697
*/
1678
1698
int sqlite3BtreeOpen(
 
1699
  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
1679
1700
  const char *zFilename,  /* Name of the file containing the BTree database */
1680
1701
  sqlite3 *db,            /* Associated database handle */
1681
1702
  Btree **ppBtree,        /* Pointer to new Btree object written here */
1682
1703
  int flags,              /* Options */
1683
1704
  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
1684
1705
){
1685
 
  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
1686
1706
  BtShared *pBt = 0;             /* Shared part of btree structure */
1687
1707
  Btree *p;                      /* Handle to return */
1688
1708
  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
1690
1710
  u8 nReserve;                   /* Byte of unused space on each page */
1691
1711
  unsigned char zDbHeader[100];  /* Database header content */
1692
1712
 
 
1713
  /* True if opening an ephemeral, temporary database */
 
1714
  const int isTempDb = zFilename==0 || zFilename[0]==0;
 
1715
 
1693
1716
  /* Set the variable isMemdb to true for an in-memory database, or 
1694
 
  ** false for a file-based database. This symbol is only required if
1695
 
  ** either of the shared-data or autovacuum features are compiled 
1696
 
  ** into the library.
 
1717
  ** false for a file-based database.
1697
1718
  */
1698
 
#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
1699
 
  #ifdef SQLITE_OMIT_MEMORYDB
1700
 
    const int isMemdb = 0;
1701
 
  #else
1702
 
    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
1703
 
  #endif
 
1719
#ifdef SQLITE_OMIT_MEMORYDB
 
1720
  const int isMemdb = 0;
 
1721
#else
 
1722
  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
 
1723
                       || (isTempDb && sqlite3TempInMemory(db));
1704
1724
#endif
1705
1725
 
1706
1726
  assert( db!=0 );
 
1727
  assert( pVfs!=0 );
1707
1728
  assert( sqlite3_mutex_held(db->mutex) );
1708
 
 
1709
 
  pVfs = db->pVfs;
 
1729
  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
 
1730
 
 
1731
  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
 
1732
  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
 
1733
 
 
1734
  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
 
1735
  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
 
1736
 
 
1737
  if( db->flags & SQLITE_NoReadlock ){
 
1738
    flags |= BTREE_NO_READLOCK;
 
1739
  }
 
1740
  if( isMemdb ){
 
1741
    flags |= BTREE_MEMORY;
 
1742
  }
 
1743
  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
 
1744
    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
 
1745
  }
1710
1746
  p = sqlite3MallocZero(sizeof(Btree));
1711
1747
  if( !p ){
1712
1748
    return SQLITE_NOMEM;
1723
1759
  ** If this Btree is a candidate for shared cache, try to find an
1724
1760
  ** existing BtShared object that we can share with
1725
1761
  */
1726
 
  if( isMemdb==0 && zFilename && zFilename[0] ){
 
1762
  if( isMemdb==0 && isTempDb==0 ){
1727
1763
    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
1728
1764
      int nFullPathname = pVfs->mxPathname+1;
1729
1765
      char *zFullPathname = sqlite3Malloc(nFullPathname);
1798
1834
    if( rc!=SQLITE_OK ){
1799
1835
      goto btree_open_out;
1800
1836
    }
 
1837
    pBt->openFlags = (u8)flags;
1801
1838
    pBt->db = db;
1802
1839
    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
1803
1840
    p->pBt = pBt;
1805
1842
    pBt->pCursor = 0;
1806
1843
    pBt->pPage1 = 0;
1807
1844
    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
1808
 
    pBt->pageSize = get2byte(&zDbHeader[16]);
 
1845
#ifdef SQLITE_SECURE_DELETE
 
1846
    pBt->secureDelete = 1;
 
1847
#endif
 
1848
    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
1809
1849
    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
1810
1850
         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
1811
1851
      pBt->pageSize = 0;
1899
1939
    sqlite3_free(pBt);
1900
1940
    sqlite3_free(p);
1901
1941
    *ppBtree = 0;
 
1942
  }else{
 
1943
    /* If the B-Tree was successfully opened, set the pager-cache size to the
 
1944
    ** default value. Except, when opening on an existing shared pager-cache,
 
1945
    ** do not change the pager-cache size.
 
1946
    */
 
1947
    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
 
1948
      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
 
1949
    }
1902
1950
  }
1903
1951
  if( mutexOpen ){
1904
1952
    assert( sqlite3_mutex_held(mutexOpen) );
2007
2055
    if( pBt->xFreeSchema && pBt->pSchema ){
2008
2056
      pBt->xFreeSchema(pBt->pSchema);
2009
2057
    }
2010
 
    sqlite3_free(pBt->pSchema);
 
2058
    sqlite3DbFree(0, pBt->pSchema);
2011
2059
    freeTempSpace(pBt);
2012
2060
    sqlite3_free(pBt);
2013
2061
  }
2056
2104
** probability of damage to near zero but with a write performance reduction.
2057
2105
*/
2058
2106
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
2059
 
int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
 
2107
int sqlite3BtreeSetSafetyLevel(
 
2108
  Btree *p,              /* The btree to set the safety level on */
 
2109
  int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
 
2110
  int fullSync,          /* PRAGMA fullfsync. */
 
2111
  int ckptFullSync       /* PRAGMA checkpoint_fullfync */
 
2112
){
2060
2113
  BtShared *pBt = p->pBt;
2061
2114
  assert( sqlite3_mutex_held(p->db->mutex) );
 
2115
  assert( level>=1 && level<=3 );
2062
2116
  sqlite3BtreeEnter(p);
2063
 
  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
 
2117
  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
2064
2118
  sqlite3BtreeLeave(p);
2065
2119
  return SQLITE_OK;
2066
2120
}
2081
2135
  return rc;
2082
2136
}
2083
2137
 
2084
 
#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
2085
2138
/*
2086
2139
** Change the default pages size and the number of reserved bytes per page.
2087
2140
** Or, if the page size has already been fixed, return SQLITE_READONLY 
2119
2172
        ((pageSize-1)&pageSize)==0 ){
2120
2173
    assert( (pageSize & 7)==0 );
2121
2174
    assert( !pBt->pPage1 && !pBt->pCursor );
2122
 
    pBt->pageSize = (u16)pageSize;
 
2175
    pBt->pageSize = (u32)pageSize;
2123
2176
    freeTempSpace(pBt);
2124
2177
  }
2125
2178
  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
2136
2189
  return p->pBt->pageSize;
2137
2190
}
2138
2191
 
 
2192
#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
2139
2193
/*
2140
2194
** Return the number of bytes of space at the end of every page that
2141
2195
** are intentually left unused.  This is the "reserved" space that is
2161
2215
  sqlite3BtreeLeave(p);
2162
2216
  return n;
2163
2217
}
 
2218
 
 
2219
/*
 
2220
** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
 
2221
** then make no changes.  Always return the value of the secureDelete
 
2222
** setting after the change.
 
2223
*/
 
2224
int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
 
2225
  int b;
 
2226
  if( p==0 ) return 0;
 
2227
  sqlite3BtreeEnter(p);
 
2228
  if( newFlag>=0 ){
 
2229
    p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
 
2230
  } 
 
2231
  b = p->pBt->secureDelete;
 
2232
  sqlite3BtreeLeave(p);
 
2233
  return b;
 
2234
}
2164
2235
#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
2165
2236
 
2166
2237
/*
2220
2291
** is returned if we run out of memory. 
2221
2292
*/
2222
2293
static int lockBtree(BtShared *pBt){
2223
 
  int rc;
2224
 
  MemPage *pPage1;
2225
 
  int nPage;
 
2294
  int rc;              /* Result code from subfunctions */
 
2295
  MemPage *pPage1;     /* Page 1 of the database file */
 
2296
  int nPage;           /* Number of pages in the database */
 
2297
  int nPageFile = 0;   /* Number of pages in the database file */
 
2298
  int nPageHeader;     /* Number of pages in the database according to hdr */
2226
2299
 
2227
2300
  assert( sqlite3_mutex_held(pBt->mutex) );
2228
2301
  assert( pBt->pPage1==0 );
2234
2307
  /* Do some checking to help insure the file we opened really is
2235
2308
  ** a valid database file. 
2236
2309
  */
2237
 
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2238
 
  if( rc!=SQLITE_OK ){
2239
 
    goto page1_init_failed;
2240
 
  }else if( nPage>0 ){
2241
 
    int pageSize;
2242
 
    int usableSize;
 
2310
  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
 
2311
  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
 
2312
  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
 
2313
    nPage = nPageFile;
 
2314
  }
 
2315
  if( nPage>0 ){
 
2316
    u32 pageSize;
 
2317
    u32 usableSize;
2243
2318
    u8 *page1 = pPage1->aData;
2244
2319
    rc = SQLITE_NOTADB;
2245
2320
    if( memcmp(page1, zMagicHeader, 16)!=0 ){
2246
2321
      goto page1_init_failed;
2247
2322
    }
 
2323
 
 
2324
#ifdef SQLITE_OMIT_WAL
2248
2325
    if( page1[18]>1 ){
2249
2326
      pBt->readOnly = 1;
2250
2327
    }
2251
2328
    if( page1[19]>1 ){
2252
2329
      goto page1_init_failed;
2253
2330
    }
 
2331
#else
 
2332
    if( page1[18]>2 ){
 
2333
      pBt->readOnly = 1;
 
2334
    }
 
2335
    if( page1[19]>2 ){
 
2336
      goto page1_init_failed;
 
2337
    }
 
2338
 
 
2339
    /* If the write version is set to 2, this database should be accessed
 
2340
    ** in WAL mode. If the log is not already open, open it now. Then 
 
2341
    ** return SQLITE_OK and return without populating BtShared.pPage1.
 
2342
    ** The caller detects this and calls this function again. This is
 
2343
    ** required as the version of page 1 currently in the page1 buffer
 
2344
    ** may not be the latest version - there may be a newer one in the log
 
2345
    ** file.
 
2346
    */
 
2347
    if( page1[19]==2 && pBt->doNotUseWAL==0 ){
 
2348
      int isOpen = 0;
 
2349
      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
 
2350
      if( rc!=SQLITE_OK ){
 
2351
        goto page1_init_failed;
 
2352
      }else if( isOpen==0 ){
 
2353
        releasePage(pPage1);
 
2354
        return SQLITE_OK;
 
2355
      }
 
2356
      rc = SQLITE_NOTADB;
 
2357
    }
 
2358
#endif
2254
2359
 
2255
2360
    /* The maximum embedded fraction must be exactly 25%.  And the minimum
2256
2361
    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
2260
2365
    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
2261
2366
      goto page1_init_failed;
2262
2367
    }
2263
 
    pageSize = get2byte(&page1[16]);
2264
 
    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
2265
 
        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
 
2368
    pageSize = (page1[16]<<8) | (page1[17]<<16);
 
2369
    if( ((pageSize-1)&pageSize)!=0
 
2370
     || pageSize>SQLITE_MAX_PAGE_SIZE 
 
2371
     || pageSize<=256 
2266
2372
    ){
2267
2373
      goto page1_init_failed;
2268
2374
    }
2269
2375
    assert( (pageSize & 7)==0 );
2270
2376
    usableSize = pageSize - page1[20];
2271
 
    if( pageSize!=pBt->pageSize ){
 
2377
    if( (u32)pageSize!=pBt->pageSize ){
2272
2378
      /* After reading the first page of the database assuming a page size
2273
2379
      ** of BtShared.pageSize, we have discovered that the page-size is
2274
2380
      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
2276
2382
      ** again with the correct page-size.
2277
2383
      */
2278
2384
      releasePage(pPage1);
2279
 
      pBt->usableSize = (u16)usableSize;
2280
 
      pBt->pageSize = (u16)pageSize;
 
2385
      pBt->usableSize = usableSize;
 
2386
      pBt->pageSize = pageSize;
2281
2387
      freeTempSpace(pBt);
2282
2388
      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
2283
2389
                                   pageSize-usableSize);
2284
2390
      return rc;
2285
2391
    }
 
2392
    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
 
2393
      rc = SQLITE_CORRUPT_BKPT;
 
2394
      goto page1_init_failed;
 
2395
    }
2286
2396
    if( usableSize<480 ){
2287
2397
      goto page1_init_failed;
2288
2398
    }
2289
 
    pBt->pageSize = (u16)pageSize;
2290
 
    pBt->usableSize = (u16)usableSize;
 
2399
    pBt->pageSize = pageSize;
 
2400
    pBt->usableSize = usableSize;
2291
2401
#ifndef SQLITE_OMIT_AUTOVACUUM
2292
2402
    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
2293
2403
    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
2303
2413
  **     9-byte nKey value
2304
2414
  **     4-byte nData value
2305
2415
  **     4-byte overflow page pointer
2306
 
  ** So a cell consists of a 2-byte poiner, a header which is as much as
 
2416
  ** So a cell consists of a 2-byte pointer, a header which is as much as
2307
2417
  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
2308
2418
  ** page pointer.
2309
2419
  */
2310
 
  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
2311
 
  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
2312
 
  pBt->maxLeaf = pBt->usableSize - 35;
2313
 
  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
 
2420
  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
 
2421
  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
 
2422
  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
 
2423
  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
2314
2424
  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
2315
2425
  pBt->pPage1 = pPage1;
 
2426
  pBt->nPage = nPage;
2316
2427
  return SQLITE_OK;
2317
2428
 
2318
2429
page1_init_failed:
2350
2461
  MemPage *pP1;
2351
2462
  unsigned char *data;
2352
2463
  int rc;
2353
 
  int nPage;
2354
2464
 
2355
2465
  assert( sqlite3_mutex_held(pBt->mutex) );
2356
 
  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
2357
 
  if( rc!=SQLITE_OK || nPage>0 ){
2358
 
    return rc;
 
2466
  if( pBt->nPage>0 ){
 
2467
    return SQLITE_OK;
2359
2468
  }
2360
2469
  pP1 = pBt->pPage1;
2361
2470
  assert( pP1!=0 );
2364
2473
  if( rc ) return rc;
2365
2474
  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
2366
2475
  assert( sizeof(zMagicHeader)==16 );
2367
 
  put2byte(&data[16], pBt->pageSize);
 
2476
  data[16] = (u8)((pBt->pageSize>>8)&0xff);
 
2477
  data[17] = (u8)((pBt->pageSize>>16)&0xff);
2368
2478
  data[18] = 1;
2369
2479
  data[19] = 1;
2370
2480
  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
2381
2491
  put4byte(&data[36 + 4*4], pBt->autoVacuum);
2382
2492
  put4byte(&data[36 + 7*4], pBt->incrVacuum);
2383
2493
#endif
 
2494
  pBt->nPage = 1;
 
2495
  data[31] = 1;
2384
2496
  return SQLITE_OK;
2385
2497
}
2386
2498
 
2470
2582
  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
2471
2583
  if( SQLITE_OK!=rc ) goto trans_begun;
2472
2584
 
 
2585
  pBt->initiallyEmpty = (u8)(pBt->nPage==0);
2473
2586
  do {
2474
2587
    /* Call lockBtree() until either pBt->pPage1 is populated or
2475
2588
    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
2494
2607
    if( rc!=SQLITE_OK ){
2495
2608
      unlockBtreeIfUnused(pBt);
2496
2609
    }
2497
 
  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
 
2610
  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
2498
2611
          btreeInvokeBusyHandler(pBt) );
2499
2612
 
2500
2613
  if( rc==SQLITE_OK ){
2513
2626
    if( p->inTrans>pBt->inTransaction ){
2514
2627
      pBt->inTransaction = p->inTrans;
2515
2628
    }
2516
 
#ifndef SQLITE_OMIT_SHARED_CACHE
2517
2629
    if( wrflag ){
 
2630
      MemPage *pPage1 = pBt->pPage1;
 
2631
#ifndef SQLITE_OMIT_SHARED_CACHE
2518
2632
      assert( !pBt->pWriter );
2519
2633
      pBt->pWriter = p;
2520
2634
      pBt->isExclusive = (u8)(wrflag>1);
 
2635
#endif
 
2636
 
 
2637
      /* If the db-size header field is incorrect (as it may be if an old
 
2638
      ** client has been writing the database file), update it now. Doing
 
2639
      ** this sooner rather than later means the database size can safely 
 
2640
      ** re-read the database size from page 1 if a savepoint or transaction
 
2641
      ** rollback occurs within the transaction.
 
2642
      */
 
2643
      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
 
2644
        rc = sqlite3PagerWrite(pPage1->pDbPage);
 
2645
        if( rc==SQLITE_OK ){
 
2646
          put4byte(&pPage1->aData[28], pBt->nPage);
 
2647
        }
 
2648
      }
2521
2649
    }
2522
 
#endif
2523
2650
  }
2524
2651
 
2525
2652
 
2749
2876
*/
2750
2877
static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
2751
2878
  Pgno nFreeList;           /* Number of pages still on the free-list */
 
2879
  int rc;
2752
2880
 
2753
2881
  assert( sqlite3_mutex_held(pBt->mutex) );
2754
2882
  assert( iLastPg>nFin );
2755
2883
 
2756
2884
  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
2757
 
    int rc;
2758
2885
    u8 eType;
2759
2886
    Pgno iPtrPage;
2760
2887
 
2830
2957
    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
2831
2958
      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
2832
2959
        MemPage *pPg;
2833
 
        int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
 
2960
        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
2834
2961
        if( rc!=SQLITE_OK ){
2835
2962
          return rc;
2836
2963
        }
2843
2970
      iLastPg--;
2844
2971
    }
2845
2972
    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
 
2973
    pBt->nPage = iLastPg;
2846
2974
  }
2847
2975
  return SQLITE_OK;
2848
2976
}
2865
2993
    rc = SQLITE_DONE;
2866
2994
  }else{
2867
2995
    invalidateAllOverflowCache(pBt);
2868
 
    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
 
2996
    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
 
2997
    if( rc==SQLITE_OK ){
 
2998
      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 
2999
      put4byte(&pBt->pPage1->aData[28], pBt->nPage);
 
3000
    }
2869
3001
  }
2870
3002
  sqlite3BtreeLeave(p);
2871
3003
  return rc;
2896
3028
    int nEntry;        /* Number of entries on one ptrmap page */
2897
3029
    Pgno nOrig;        /* Database size before freeing */
2898
3030
 
2899
 
    nOrig = pagerPagecount(pBt);
 
3031
    nOrig = btreePagecount(pBt);
2900
3032
    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
2901
3033
      /* It is not possible to create a database for which the final page
2902
3034
      ** is either a pointer-map page or the pending-byte page. If one
2921
3053
      rc = incrVacuumStep(pBt, nFin, iFree);
2922
3054
    }
2923
3055
    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
2924
 
      rc = SQLITE_OK;
2925
3056
      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
2926
3057
      put4byte(&pBt->pPage1->aData[32], 0);
2927
3058
      put4byte(&pBt->pPage1->aData[36], 0);
 
3059
      put4byte(&pBt->pPage1->aData[28], nFin);
2928
3060
      sqlite3PagerTruncateImage(pBt->pPager, nFin);
 
3061
      pBt->nPage = nFin;
2929
3062
    }
2930
3063
    if( rc!=SQLITE_OK ){
2931
3064
      sqlite3PagerRollback(pPager);
3035
3168
** the rollback journal (which causes the transaction to commit) and
3036
3169
** drop locks.
3037
3170
**
 
3171
** Normally, if an error occurs while the pager layer is attempting to 
 
3172
** finalize the underlying journal file, this function returns an error and
 
3173
** the upper layer will attempt a rollback. However, if the second argument
 
3174
** is non-zero then this b-tree transaction is part of a multi-file 
 
3175
** transaction. In this case, the transaction has already been committed 
 
3176
** (by deleting a master journal file) and the caller will ignore this 
 
3177
** functions return code. So, even if an error occurs in the pager layer,
 
3178
** reset the b-tree objects internal state to indicate that the write
 
3179
** transaction has been closed. This is quite safe, as the pager will have
 
3180
** transitioned to the error state.
 
3181
**
3038
3182
** This will release the write lock on the database file.  If there
3039
3183
** are no active cursors, it also releases the read lock.
3040
3184
*/
3041
 
int sqlite3BtreeCommitPhaseTwo(Btree *p){
3042
 
  BtShared *pBt = p->pBt;
 
3185
int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
3043
3186
 
 
3187
  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
3044
3188
  sqlite3BtreeEnter(p);
3045
3189
  btreeIntegrity(p);
3046
3190
 
3049
3193
  */
3050
3194
  if( p->inTrans==TRANS_WRITE ){
3051
3195
    int rc;
 
3196
    BtShared *pBt = p->pBt;
3052
3197
    assert( pBt->inTransaction==TRANS_WRITE );
3053
3198
    assert( pBt->nTransaction>0 );
3054
3199
    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
3055
 
    if( rc!=SQLITE_OK ){
 
3200
    if( rc!=SQLITE_OK && bCleanup==0 ){
3056
3201
      sqlite3BtreeLeave(p);
3057
3202
      return rc;
3058
3203
    }
3072
3217
  sqlite3BtreeEnter(p);
3073
3218
  rc = sqlite3BtreeCommitPhaseOne(p, 0);
3074
3219
  if( rc==SQLITE_OK ){
3075
 
    rc = sqlite3BtreeCommitPhaseTwo(p);
 
3220
    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
3076
3221
  }
3077
3222
  sqlite3BtreeLeave(p);
3078
3223
  return rc;
3175
3320
    ** call btreeGetPage() on page 1 again to make
3176
3321
    ** sure pPage1->aData is set correctly. */
3177
3322
    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
 
3323
      int nPage = get4byte(28+(u8*)pPage1->aData);
 
3324
      testcase( nPage==0 );
 
3325
      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
 
3326
      testcase( pBt->nPage!=nPage );
 
3327
      pBt->nPage = nPage;
3178
3328
      releasePage(pPage1);
3179
3329
    }
3180
3330
    assert( countWriteCursors(pBt)==0 );
3212
3362
  assert( pBt->readOnly==0 );
3213
3363
  assert( iStatement>0 );
3214
3364
  assert( iStatement>p->db->nSavepoint );
3215
 
  if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
3216
 
    rc = SQLITE_INTERNAL;
3217
 
  }else{
3218
 
    assert( pBt->inTransaction==TRANS_WRITE );
3219
 
    /* At the pager level, a statement transaction is a savepoint with
3220
 
    ** an index greater than all savepoints created explicitly using
3221
 
    ** SQL statements. It is illegal to open, release or rollback any
3222
 
    ** such savepoints while the statement transaction savepoint is active.
3223
 
    */
3224
 
    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
3225
 
  }
 
3365
  assert( pBt->inTransaction==TRANS_WRITE );
 
3366
  /* At the pager level, a statement transaction is a savepoint with
 
3367
  ** an index greater than all savepoints created explicitly using
 
3368
  ** SQL statements. It is illegal to open, release or rollback any
 
3369
  ** such savepoints while the statement transaction savepoint is active.
 
3370
  */
 
3371
  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
3226
3372
  sqlite3BtreeLeave(p);
3227
3373
  return rc;
3228
3374
}
3248
3394
    sqlite3BtreeEnter(p);
3249
3395
    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
3250
3396
    if( rc==SQLITE_OK ){
 
3397
      if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
3251
3398
      rc = newDatabase(pBt);
 
3399
      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
 
3400
 
 
3401
      /* The database size was written into the offset 28 of the header
 
3402
      ** when the transaction started, so we know that the value at offset
 
3403
      ** 28 is nonzero. */
 
3404
      assert( pBt->nPage>0 );
3252
3405
    }
3253
3406
    sqlite3BtreeLeave(p);
3254
3407
  }
3314
3467
  if( NEVER(wrFlag && pBt->readOnly) ){
3315
3468
    return SQLITE_READONLY;
3316
3469
  }
3317
 
  if( iTable==1 && pagerPagecount(pBt)==0 ){
 
3470
  if( iTable==1 && btreePagecount(pBt)==0 ){
3318
3471
    return SQLITE_EMPTY;
3319
3472
  }
3320
3473
 
3585
3738
      iGuess++;
3586
3739
    }
3587
3740
 
3588
 
    if( iGuess<=pagerPagecount(pBt) ){
 
3741
    if( iGuess<=btreePagecount(pBt) ){
3589
3742
      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
3590
3743
      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
3591
3744
        next = iGuess;
4180
4333
    if( pCur->eState==CURSOR_INVALID ){
4181
4334
      assert( pCur->apPage[pCur->iPage]->nCell==0 );
4182
4335
      *pRes = 1;
4183
 
      rc = SQLITE_OK;
4184
4336
    }else{
4185
4337
      assert( pCur->apPage[pCur->iPage]->nCell>0 );
4186
4338
      *pRes = 0;
4301
4453
  }
4302
4454
  assert( pCur->apPage[0]->intKey || pIdxKey );
4303
4455
  for(;;){
4304
 
    int lwr, upr;
 
4456
    int lwr, upr, idx;
4305
4457
    Pgno chldPg;
4306
4458
    MemPage *pPage = pCur->apPage[pCur->iPage];
4307
4459
    int c;
4317
4469
    lwr = 0;
4318
4470
    upr = pPage->nCell-1;
4319
4471
    if( biasRight ){
4320
 
      pCur->aiIdx[pCur->iPage] = (u16)upr;
 
4472
      pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
4321
4473
    }else{
4322
 
      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
 
4474
      pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
4323
4475
    }
4324
4476
    for(;;){
4325
 
      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
4326
4477
      u8 *pCell;                          /* Pointer to current cell in pPage */
4327
4478
 
 
4479
      assert( idx==pCur->aiIdx[pCur->iPage] );
4328
4480
      pCur->info.nSize = 0;
4329
4481
      pCell = findCell(pPage, idx) + pPage->childPtrSize;
4330
4482
      if( pPage->intKey ){
4345
4497
        pCur->validNKey = 1;
4346
4498
        pCur->info.nKey = nCellKey;
4347
4499
      }else{
4348
 
        /* The maximum supported page-size is 32768 bytes. This means that
 
4500
        /* The maximum supported page-size is 65536 bytes. This means that
4349
4501
        ** the maximum number of record bytes stored on an index B-Tree
4350
 
        ** page is at most 8198 bytes, which may be stored as a 2-byte
 
4502
        ** page is less than 16384 bytes and may be stored as a 2-byte
4351
4503
        ** varint. This information is used to attempt to avoid parsing 
4352
4504
        ** the entire cell by checking for the cases where the record is 
4353
4505
        ** stored entirely within the b-tree page by inspecting the first 
4407
4559
      if( lwr>upr ){
4408
4560
        break;
4409
4561
      }
4410
 
      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
 
4562
      pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
4411
4563
    }
4412
4564
    assert( lwr==upr+1 );
4413
4565
    assert( pPage->isInit );
4617
4769
 
4618
4770
  assert( sqlite3_mutex_held(pBt->mutex) );
4619
4771
  pPage1 = pBt->pPage1;
4620
 
  mxPage = pagerPagecount(pBt);
 
4772
  mxPage = btreePagecount(pBt);
4621
4773
  n = get4byte(&pPage1->aData[36]);
4622
4774
  testcase( n==mxPage-1 );
4623
4775
  if( n>=mxPage ){
4675
4827
        goto end_allocate_page;
4676
4828
      }
4677
4829
 
4678
 
      k = get4byte(&pTrunk->aData[4]);
 
4830
      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
4679
4831
      if( k==0 && !searchList ){
4680
4832
        /* The trunk has no leaves and the list is not being searched. 
4681
4833
        ** So extract the trunk page itself and use it as the newly 
4710
4862
          if( !pPrevTrunk ){
4711
4863
            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
4712
4864
          }else{
 
4865
            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
 
4866
            if( rc!=SQLITE_OK ){
 
4867
              goto end_allocate_page;
 
4868
            }
4713
4869
            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
4714
4870
          }
4715
4871
        }else{
4756
4912
        u32 closest;
4757
4913
        Pgno iPage;
4758
4914
        unsigned char *aData = pTrunk->aData;
4759
 
        rc = sqlite3PagerWrite(pTrunk->pDbPage);
4760
 
        if( rc ){
4761
 
          goto end_allocate_page;
4762
 
        }
4763
4915
        if( nearby>0 ){
4764
4916
          u32 i;
4765
4917
          int dist;
4766
4918
          closest = 0;
4767
 
          dist = get4byte(&aData[8]) - nearby;
4768
 
          if( dist<0 ) dist = -dist;
 
4919
          dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
4769
4920
          for(i=1; i<k; i++){
4770
 
            int d2 = get4byte(&aData[8+i*4]) - nearby;
4771
 
            if( d2<0 ) d2 = -d2;
 
4921
            int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
4772
4922
            if( d2<dist ){
4773
4923
              closest = i;
4774
4924
              dist = d2;
4791
4941
          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
4792
4942
                 ": %d more free pages\n",
4793
4943
                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
 
4944
          rc = sqlite3PagerWrite(pTrunk->pDbPage);
 
4945
          if( rc ) goto end_allocate_page;
4794
4946
          if( closest<k-1 ){
4795
4947
            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
4796
4948
          }
4797
4949
          put4byte(&aData[4], k-1);
4798
 
          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
4799
4950
          noContent = !btreeGetHasContent(pBt, *pPgno);
4800
4951
          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
4801
4952
          if( rc==SQLITE_OK ){
4813
4964
  }else{
4814
4965
    /* There are no pages on the freelist, so create a new page at the
4815
4966
    ** end of the file */
4816
 
    int nPage = pagerPagecount(pBt);
4817
 
    *pPgno = nPage + 1;
4818
 
 
4819
 
    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
4820
 
      (*pPgno)++;
4821
 
    }
 
4967
    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 
4968
    if( rc ) return rc;
 
4969
    pBt->nPage++;
 
4970
    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
4822
4971
 
4823
4972
#ifndef SQLITE_OMIT_AUTOVACUUM
4824
 
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
 
4973
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
4825
4974
      /* If *pPgno refers to a pointer-map page, allocate two new pages
4826
4975
      ** at the end of the file instead of one. The first allocated page
4827
4976
      ** becomes a new pointer-map page, the second is used by the caller.
4828
4977
      */
4829
4978
      MemPage *pPg = 0;
4830
 
      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
4831
 
      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
4832
 
      rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
 
4979
      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
 
4980
      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
 
4981
      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
4833
4982
      if( rc==SQLITE_OK ){
4834
4983
        rc = sqlite3PagerWrite(pPg->pDbPage);
4835
4984
        releasePage(pPg);
4836
4985
      }
4837
4986
      if( rc ) return rc;
4838
 
      (*pPgno)++;
4839
 
      if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
 
4987
      pBt->nPage++;
 
4988
      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
4840
4989
    }
4841
4990
#endif
 
4991
    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
 
4992
    *pPgno = pBt->nPage;
4842
4993
 
4843
4994
    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
4844
 
    rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
 
4995
    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
4845
4996
    if( rc ) return rc;
4846
4997
    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
4847
4998
    if( rc!=SQLITE_OK ){
4864
5015
  }else{
4865
5016
    *ppPage = 0;
4866
5017
  }
 
5018
  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
4867
5019
  return rc;
4868
5020
}
4869
5021
 
4904
5056
  nFree = get4byte(&pPage1->aData[36]);
4905
5057
  put4byte(&pPage1->aData[36], nFree+1);
4906
5058
 
4907
 
#ifdef SQLITE_SECURE_DELETE
4908
 
  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
4909
 
  ** always fully overwrite deleted information with zeros.
4910
 
  */
4911
 
  if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
4912
 
   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
4913
 
  ){
4914
 
    goto freepage_out;
 
5059
  if( pBt->secureDelete ){
 
5060
    /* If the secure_delete option is enabled, then
 
5061
    ** always fully overwrite deleted information with zeros.
 
5062
    */
 
5063
    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
 
5064
     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
 
5065
    ){
 
5066
      goto freepage_out;
 
5067
    }
 
5068
    memset(pPage->aData, 0, pPage->pBt->pageSize);
4915
5069
  }
4916
 
  memset(pPage->aData, 0, pPage->pBt->pageSize);
4917
 
#endif
4918
5070
 
4919
5071
  /* If the database supports auto-vacuum, write an entry in the pointer-map
4920
5072
  ** to indicate that the page is free.
4965
5117
      if( rc==SQLITE_OK ){
4966
5118
        put4byte(&pTrunk->aData[4], nLeaf+1);
4967
5119
        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
4968
 
#ifndef SQLITE_SECURE_DELETE
4969
 
        if( pPage ){
 
5120
        if( pPage && !pBt->secureDelete ){
4970
5121
          sqlite3PagerDontWrite(pPage->pDbPage);
4971
5122
        }
4972
 
#endif
4973
5123
        rc = btreeSetHasContent(pBt, iPage);
4974
5124
      }
4975
5125
      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
5018
5168
  Pgno ovflPgno;
5019
5169
  int rc;
5020
5170
  int nOvfl;
5021
 
  u16 ovflPageSize;
 
5171
  u32 ovflPageSize;
5022
5172
 
5023
5173
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5024
5174
  btreeParseCellPtr(pPage, pCell, &info);
5033
5183
  while( nOvfl-- ){
5034
5184
    Pgno iNext = 0;
5035
5185
    MemPage *pOvfl = 0;
5036
 
    if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
 
5186
    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
5037
5187
      /* 0 is not a legal page number and page 1 cannot be an 
5038
5188
      ** overflow page. Therefore if ovflPgno<2 or past the end of the 
5039
5189
      ** file the database must be corrupt. */
5043
5193
      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
5044
5194
      if( rc ) return rc;
5045
5195
    }
5046
 
    rc = freePage2(pBt, pOvfl, ovflPgno);
 
5196
 
 
5197
    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
 
5198
     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
 
5199
    ){
 
5200
      /* There is no reason any cursor should have an outstanding reference 
 
5201
      ** to an overflow page belonging to a cell that is being deleted/updated.
 
5202
      ** So if there exists more than one reference to this page, then it 
 
5203
      ** must not really be an overflow page and the database must be corrupt. 
 
5204
      ** It is helpful to detect this before calling freePage2(), as 
 
5205
      ** freePage2() may zero the page contents if secure-delete mode is
 
5206
      ** enabled. If this 'overflow' page happens to be a page that the
 
5207
      ** caller is iterating through or using in some other way, this
 
5208
      ** can be problematic.
 
5209
      */
 
5210
      rc = SQLITE_CORRUPT_BKPT;
 
5211
    }else{
 
5212
      rc = freePage2(pBt, pOvfl, ovflPgno);
 
5213
    }
 
5214
 
5047
5215
    if( pOvfl ){
5048
5216
      sqlite3PagerUnref(pOvfl->pDbPage);
5049
5217
    }
5224
5392
** "sz" must be the number of bytes in the cell.
5225
5393
*/
5226
5394
static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
5227
 
  int i;          /* Loop counter */
5228
 
  int pc;         /* Offset to cell content of cell being deleted */
 
5395
  u32 pc;         /* Offset to cell content of cell being deleted */
5229
5396
  u8 *data;       /* pPage->aData */
5230
5397
  u8 *ptr;        /* Used to move bytes around within data[] */
 
5398
  u8 *endPtr;     /* End of loop */
5231
5399
  int rc;         /* The return code */
5232
5400
  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
5233
5401
 
5243
5411
  hdr = pPage->hdrOffset;
5244
5412
  testcase( pc==get2byte(&data[hdr+5]) );
5245
5413
  testcase( pc+sz==pPage->pBt->usableSize );
5246
 
  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
 
5414
  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
5247
5415
    *pRC = SQLITE_CORRUPT_BKPT;
5248
5416
    return;
5249
5417
  }
5252
5420
    *pRC = rc;
5253
5421
    return;
5254
5422
  }
5255
 
  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
5256
 
    ptr[0] = ptr[2];
5257
 
    ptr[1] = ptr[3];
 
5423
  endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
 
5424
  assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
 
5425
  while( ptr<endPtr ){
 
5426
    *(u16*)ptr = *(u16*)&ptr[2];
 
5427
    ptr += 2;
5258
5428
  }
5259
5429
  pPage->nCell--;
5260
5430
  put2byte(&data[hdr+3], pPage->nCell);
5287
5457
  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
5288
5458
  int *pRC          /* Read and write return code from here */
5289
5459
){
5290
 
  int idx;          /* Where to write new cell content in data[] */
 
5460
  int idx = 0;      /* Where to write new cell content in data[] */
5291
5461
  int j;            /* Loop counter */
5292
5462
  int end;          /* First byte past the last cell pointer in data[] */
5293
5463
  int ins;          /* Index in data[] where new cell pointer is inserted */
5294
5464
  int cellOffset;   /* Address of first cell pointer in data[] */
5295
5465
  u8 *data;         /* The content of the whole page */
5296
5466
  u8 *ptr;          /* Used for moving information around in data[] */
 
5467
  u8 *endPtr;       /* End of the loop */
5297
5468
 
5298
5469
  int nSkip = (iChild ? 4 : 0);
5299
5470
 
5300
5471
  if( *pRC ) return;
5301
5472
 
5302
5473
  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
5303
 
  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
 
5474
  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
5304
5475
  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
5305
5476
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5306
5477
  /* The cell should normally be sized correctly.  However, when moving a
5337
5508
    /* The allocateSpace() routine guarantees the following two properties
5338
5509
    ** if it returns success */
5339
5510
    assert( idx >= end+2 );
5340
 
    assert( idx+sz <= pPage->pBt->usableSize );
 
5511
    assert( idx+sz <= (int)pPage->pBt->usableSize );
5341
5512
    pPage->nCell++;
5342
5513
    pPage->nFree -= (u16)(2 + sz);
5343
5514
    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
5344
5515
    if( iChild ){
5345
5516
      put4byte(&data[idx], iChild);
5346
5517
    }
5347
 
    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
5348
 
      ptr[0] = ptr[-2];
5349
 
      ptr[1] = ptr[-1];
 
5518
    ptr = &data[end];
 
5519
    endPtr = &data[ins];
 
5520
    assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
 
5521
    while( ptr>endPtr ){
 
5522
      *(u16*)ptr = *(u16*)&ptr[-2];
 
5523
      ptr -= 2;
5350
5524
    }
5351
5525
    put2byte(&data[ins], idx);
5352
5526
    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
5380
5554
 
5381
5555
  assert( pPage->nOverflow==0 );
5382
5556
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
5383
 
  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
 
5557
  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
 
5558
            && (int)MX_CELL(pPage->pBt)<=10921);
5384
5559
  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
5385
5560
 
5386
5561
  /* Check that the page has just been zeroed by zeroPage() */
5387
5562
  assert( pPage->nCell==0 );
5388
 
  assert( get2byte(&data[hdr+5])==nUsable );
 
5563
  assert( get2byteNotZero(&data[hdr+5])==nUsable );
5389
5564
 
5390
5565
  pCellptr = &data[pPage->cellOffset + nCell*2];
5391
5566
  cellbody = nUsable;
5392
5567
  for(i=nCell-1; i>=0; i--){
 
5568
    u16 sz = aSize[i];
5393
5569
    pCellptr -= 2;
5394
 
    cellbody -= aSize[i];
 
5570
    cellbody -= sz;
5395
5571
    put2byte(pCellptr, cellbody);
5396
 
    memcpy(&data[cellbody], apCell[i], aSize[i]);
 
5572
    memcpy(&data[cellbody], apCell[i], sz);
5397
5573
  }
5398
5574
  put2byte(&data[hdr+3], nCell);
5399
5575
  put2byte(&data[hdr+5], cellbody);
5451
5627
  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
5452
5628
  assert( pPage->nOverflow==1 );
5453
5629
 
 
5630
  /* This error condition is now caught prior to reaching this function */
5454
5631
  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
5455
5632
 
5456
5633
  /* Allocate a new page. This page will become the right-sibling of 
5593
5770
  
5594
5771
    assert( pFrom->isInit );
5595
5772
    assert( pFrom->nFree>=iToHdr );
5596
 
    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
 
5773
    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
5597
5774
  
5598
5775
    /* Copy the b-tree node content from page pFrom to page pTo. */
5599
5776
    iData = get2byte(&aFrom[iFromHdr+5]);
5778
5955
      ** In this case, temporarily copy the cell into the aOvflSpace[]
5779
5956
      ** buffer. It will be copied out again as soon as the aSpace[] buffer
5780
5957
      ** is allocated.  */
5781
 
#ifdef SQLITE_SECURE_DELETE
5782
 
      memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
5783
 
      apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
5784
 
#endif
 
5958
      if( pBt->secureDelete ){
 
5959
        int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
 
5960
        if( (iOff+szNew[i])>(int)pBt->usableSize ){
 
5961
          rc = SQLITE_CORRUPT_BKPT;
 
5962
          memset(apOld, 0, (i+1)*sizeof(MemPage*));
 
5963
          goto balance_cleanup;
 
5964
        }else{
 
5965
          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
 
5966
          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
 
5967
        }
 
5968
      }
5785
5969
      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
5786
5970
    }
5787
5971
  }
5839
6023
    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
5840
6024
 
5841
6025
    limit = pOld->nCell+pOld->nOverflow;
5842
 
    for(j=0; j<limit; j++){
5843
 
      assert( nCell<nMaxCells );
5844
 
      apCell[nCell] = findOverflowCell(pOld, j);
5845
 
      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
5846
 
      nCell++;
5847
 
    }
 
6026
    if( pOld->nOverflow>0 ){
 
6027
      for(j=0; j<limit; j++){
 
6028
        assert( nCell<nMaxCells );
 
6029
        apCell[nCell] = findOverflowCell(pOld, j);
 
6030
        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
 
6031
        nCell++;
 
6032
      }
 
6033
    }else{
 
6034
      u8 *aData = pOld->aData;
 
6035
      u16 maskPage = pOld->maskPage;
 
6036
      u16 cellOffset = pOld->cellOffset;
 
6037
      for(j=0; j<limit; j++){
 
6038
        assert( nCell<nMaxCells );
 
6039
        apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
 
6040
        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
 
6041
        nCell++;
 
6042
      }
 
6043
    }       
5848
6044
    if( i<nOld-1 && !leafData){
5849
6045
      u16 sz = (u16)szNew[i];
5850
6046
      u8 *pTemp;
5852
6048
      szCell[nCell] = sz;
5853
6049
      pTemp = &aSpace1[iSpace1];
5854
6050
      iSpace1 += sz;
5855
 
      assert( sz<=pBt->pageSize/4 );
5856
 
      assert( iSpace1<=pBt->pageSize );
 
6051
      assert( sz<=pBt->maxLocal+23 );
 
6052
      assert( iSpace1 <= (int)pBt->pageSize );
5857
6053
      memcpy(pTemp, apDiv[i], sz);
5858
6054
      apCell[nCell] = pTemp+leafCorrection;
5859
6055
      assert( leafCorrection==0 || leafCorrection==4 );
5901
6097
      if( leafData ){ i--; }
5902
6098
      subtotal = 0;
5903
6099
      k++;
5904
 
      if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
 
6100
      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
5905
6101
    }
5906
6102
  }
5907
6103
  szNew[k] = subtotal;
5955
6151
  ** Allocate k new pages.  Reuse old pages where possible.
5956
6152
  */
5957
6153
  if( apOld[0]->pgno<=1 ){
5958
 
    rc = SQLITE_CORRUPT;
 
6154
    rc = SQLITE_CORRUPT_BKPT;
5959
6155
    goto balance_cleanup;
5960
6156
  }
5961
6157
  pageFlags = apOld[0]->aData[0];
6018
6214
      }
6019
6215
    }
6020
6216
    if( minI>i ){
6021
 
      int t;
6022
6217
      MemPage *pT;
6023
 
      t = apNew[i]->pgno;
6024
6218
      pT = apNew[i];
6025
6219
      apNew[i] = apNew[minI];
6026
6220
      apNew[minI] = pT;
6098
6292
        }
6099
6293
      }
6100
6294
      iOvflSpace += sz;
6101
 
      assert( sz<=pBt->pageSize/4 );
6102
 
      assert( iOvflSpace<=pBt->pageSize );
 
6295
      assert( sz<=pBt->maxLocal+23 );
 
6296
      assert( iOvflSpace <= (int)pBt->pageSize );
6103
6297
      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
6104
6298
      if( rc!=SQLITE_OK ) goto balance_cleanup;
6105
6299
      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
6544
6738
  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
6545
6739
  if( rc ) goto end_insert;
6546
6740
  assert( szNew==cellSizePtr(pPage, newCell) );
6547
 
  assert( szNew<=MX_CELL_SIZE(pBt) );
 
6741
  assert( szNew <= MX_CELL_SIZE(pBt) );
6548
6742
  idx = pCur->aiIdx[pCur->iPage];
6549
6743
  if( loc==0 ){
6550
6744
    u16 szOld;
6684
6878
 
6685
6879
    pCell = findCell(pLeaf, pLeaf->nCell-1);
6686
6880
    nCell = cellSizePtr(pLeaf, pCell);
6687
 
    assert( MX_CELL_SIZE(pBt)>=nCell );
 
6881
    assert( MX_CELL_SIZE(pBt) >= nCell );
6688
6882
 
6689
6883
    allocateTempSpace(pBt);
6690
6884
    pTmp = pBt->pTmpSpace;
6735
6929
**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
6736
6930
**     BTREE_ZERODATA                  Used for SQL indices
6737
6931
*/
6738
 
static int btreeCreateTable(Btree *p, int *piTable, int flags){
 
6932
static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
6739
6933
  BtShared *pBt = p->pBt;
6740
6934
  MemPage *pRoot;
6741
6935
  Pgno pgnoRoot;
6742
6936
  int rc;
 
6937
  int ptfFlags;          /* Page-type flage for the root page of new table */
6743
6938
 
6744
6939
  assert( sqlite3BtreeHoldsMutex(p) );
6745
6940
  assert( pBt->inTransaction==TRANS_WRITE );
6840
7035
      releasePage(pRoot);
6841
7036
      return rc;
6842
7037
    }
 
7038
 
 
7039
    /* When the new root page was allocated, page 1 was made writable in
 
7040
    ** order either to increase the database filesize, or to decrement the
 
7041
    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
 
7042
    */
 
7043
    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
6843
7044
    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
6844
 
    if( rc ){
 
7045
    if( NEVER(rc) ){
6845
7046
      releasePage(pRoot);
6846
7047
      return rc;
6847
7048
    }
6852
7053
  }
6853
7054
#endif
6854
7055
  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
6855
 
  zeroPage(pRoot, flags | PTF_LEAF);
 
7056
  if( createTabFlags & BTREE_INTKEY ){
 
7057
    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
 
7058
  }else{
 
7059
    ptfFlags = PTF_ZERODATA | PTF_LEAF;
 
7060
  }
 
7061
  zeroPage(pRoot, ptfFlags);
6856
7062
  sqlite3PagerUnref(pRoot->pDbPage);
 
7063
  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
6857
7064
  *piTable = (int)pgnoRoot;
6858
7065
  return SQLITE_OK;
6859
7066
}
6881
7088
  int i;
6882
7089
 
6883
7090
  assert( sqlite3_mutex_held(pBt->mutex) );
6884
 
  if( pgno>pagerPagecount(pBt) ){
 
7091
  if( pgno>btreePagecount(pBt) ){
6885
7092
    return SQLITE_CORRUPT_BKPT;
6886
7093
  }
6887
7094
 
7336
7543
        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
7337
7544
      }
7338
7545
#endif
7339
 
      if( n>pCheck->pBt->usableSize/4-2 ){
 
7546
      if( n>(int)pCheck->pBt->usableSize/4-2 ){
7340
7547
        checkAppendMsg(pCheck, zContext,
7341
7548
           "freelist leaf count too big on page %d", iPage);
7342
7549
        N--;
7393
7600
static int checkTreePage(
7394
7601
  IntegrityCk *pCheck,  /* Context for the sanity check */
7395
7602
  int iPage,            /* Page number of the page to check */
7396
 
  char *zParentContext  /* Parent context */
 
7603
  char *zParentContext, /* Parent context */
 
7604
  i64 *pnParentMinKey, 
 
7605
  i64 *pnParentMaxKey
7397
7606
){
7398
7607
  MemPage *pPage;
7399
7608
  int i, rc, depth, d2, pgno, cnt;
7404
7613
  int usableSize;
7405
7614
  char zContext[100];
7406
7615
  char *hit = 0;
 
7616
  i64 nMinKey = 0;
 
7617
  i64 nMaxKey = 0;
7407
7618
 
7408
7619
  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
7409
7620
 
7446
7657
    btreeParseCellPtr(pPage, pCell, &info);
7447
7658
    sz = info.nData;
7448
7659
    if( !pPage->intKey ) sz += (int)info.nKey;
 
7660
    /* For intKey pages, check that the keys are in order.
 
7661
    */
 
7662
    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
 
7663
    else{
 
7664
      if( info.nKey <= nMaxKey ){
 
7665
        checkAppendMsg(pCheck, zContext, 
 
7666
            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
 
7667
      }
 
7668
      nMaxKey = info.nKey;
 
7669
    }
7449
7670
    assert( sz==info.nPayload );
7450
7671
    if( (sz>info.nLocal) 
7451
7672
     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
7469
7690
        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7470
7691
      }
7471
7692
#endif
7472
 
      d2 = checkTreePage(pCheck, pgno, zContext);
 
7693
      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
7473
7694
      if( i>0 && d2!=depth ){
7474
7695
        checkAppendMsg(pCheck, zContext, "Child page depth differs");
7475
7696
      }
7476
7697
      depth = d2;
7477
7698
    }
7478
7699
  }
 
7700
 
7479
7701
  if( !pPage->leaf ){
7480
7702
    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
7481
7703
    sqlite3_snprintf(sizeof(zContext), zContext, 
7482
7704
                     "On page %d at right child: ", iPage);
7483
7705
#ifndef SQLITE_OMIT_AUTOVACUUM
7484
7706
    if( pBt->autoVacuum ){
7485
 
      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
 
7707
      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
7486
7708
    }
7487
7709
#endif
7488
 
    checkTreePage(pCheck, pgno, zContext);
 
7710
    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
7489
7711
  }
7490
7712
 
 
7713
  /* For intKey leaf pages, check that the min/max keys are in order
 
7714
  ** with any left/parent/right pages.
 
7715
  */
 
7716
  if( pPage->leaf && pPage->intKey ){
 
7717
    /* if we are a left child page */
 
7718
    if( pnParentMinKey ){
 
7719
      /* if we are the left most child page */
 
7720
      if( !pnParentMaxKey ){
 
7721
        if( nMaxKey > *pnParentMinKey ){
 
7722
          checkAppendMsg(pCheck, zContext, 
 
7723
              "Rowid %lld out of order (max larger than parent min of %lld)",
 
7724
              nMaxKey, *pnParentMinKey);
 
7725
        }
 
7726
      }else{
 
7727
        if( nMinKey <= *pnParentMinKey ){
 
7728
          checkAppendMsg(pCheck, zContext, 
 
7729
              "Rowid %lld out of order (min less than parent min of %lld)",
 
7730
              nMinKey, *pnParentMinKey);
 
7731
        }
 
7732
        if( nMaxKey > *pnParentMaxKey ){
 
7733
          checkAppendMsg(pCheck, zContext, 
 
7734
              "Rowid %lld out of order (max larger than parent max of %lld)",
 
7735
              nMaxKey, *pnParentMaxKey);
 
7736
        }
 
7737
        *pnParentMinKey = nMaxKey;
 
7738
      }
 
7739
    /* else if we're a right child page */
 
7740
    } else if( pnParentMaxKey ){
 
7741
      if( nMinKey <= *pnParentMaxKey ){
 
7742
        checkAppendMsg(pCheck, zContext, 
 
7743
            "Rowid %lld out of order (min less than parent max of %lld)",
 
7744
            nMinKey, *pnParentMaxKey);
 
7745
      }
 
7746
    }
 
7747
  }
 
7748
 
7491
7749
  /* Check for complete coverage of the page
7492
7750
  */
7493
7751
  data = pPage->aData;
7496
7754
  if( hit==0 ){
7497
7755
    pCheck->mallocFailed = 1;
7498
7756
  }else{
7499
 
    u16 contentOffset = get2byte(&data[hdr+5]);
 
7757
    int contentOffset = get2byteNotZero(&data[hdr+5]);
7500
7758
    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
7501
7759
    memset(hit+contentOffset, 0, usableSize-contentOffset);
7502
7760
    memset(hit, 1, contentOffset);
7504
7762
    cellStart = hdr + 12 - 4*pPage->leaf;
7505
7763
    for(i=0; i<nCell; i++){
7506
7764
      int pc = get2byte(&data[cellStart+i*2]);
7507
 
      u16 size = 1024;
 
7765
      u32 size = 65536;
7508
7766
      int j;
7509
7767
      if( pc<=usableSize-4 ){
7510
7768
        size = cellSizePtr(pPage, &data[pc]);
7511
7769
      }
7512
 
      if( (pc+size-1)>=usableSize ){
 
7770
      if( (int)(pc+size-1)>=usableSize ){
7513
7771
        checkAppendMsg(pCheck, 0, 
7514
 
            "Corruption detected in cell %d on page %d",i,iPage,0);
 
7772
            "Corruption detected in cell %d on page %d",i,iPage);
7515
7773
      }else{
7516
7774
        for(j=pc+size-1; j>=pc; j--) hit[j]++;
7517
7775
      }
7581
7839
  nRef = sqlite3PagerRefcount(pBt->pPager);
7582
7840
  sCheck.pBt = pBt;
7583
7841
  sCheck.pPager = pBt->pPager;
7584
 
  sCheck.nPage = pagerPagecount(sCheck.pBt);
 
7842
  sCheck.nPage = btreePagecount(sCheck.pBt);
7585
7843
  sCheck.mxErr = mxErr;
7586
7844
  sCheck.nErr = 0;
7587
7845
  sCheck.mallocFailed = 0;
7602
7860
    sCheck.anRef[i] = 1;
7603
7861
  }
7604
7862
  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
 
7863
  sCheck.errMsg.useMalloc = 2;
7605
7864
 
7606
7865
  /* Check the integrity of the freelist
7607
7866
  */
7617
7876
      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
7618
7877
    }
7619
7878
#endif
7620
 
    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
 
7879
    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
7621
7880
  }
7622
7881
 
7623
7882
  /* Make sure every page in the file is referenced
7700
7959
  return (p && (p->inTrans==TRANS_WRITE));
7701
7960
}
7702
7961
 
 
7962
#ifndef SQLITE_OMIT_WAL
 
7963
/*
 
7964
** Run a checkpoint on the Btree passed as the first argument.
 
7965
**
 
7966
** Return SQLITE_LOCKED if this or any other connection has an open 
 
7967
** transaction on the shared-cache the argument Btree is connected to.
 
7968
**
 
7969
** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
 
7970
*/
 
7971
int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
 
7972
  int rc = SQLITE_OK;
 
7973
  if( p ){
 
7974
    BtShared *pBt = p->pBt;
 
7975
    sqlite3BtreeEnter(p);
 
7976
    if( pBt->inTransaction!=TRANS_NONE ){
 
7977
      rc = SQLITE_LOCKED;
 
7978
    }else{
 
7979
      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
 
7980
    }
 
7981
    sqlite3BtreeLeave(p);
 
7982
  }
 
7983
  return rc;
 
7984
}
 
7985
#endif
 
7986
 
7703
7987
/*
7704
7988
** Return non-zero if a read (or write) transaction is active.
7705
7989
*/
7732
8016
**
7733
8017
** Just before the shared-btree is closed, the function passed as the 
7734
8018
** xFree argument when the memory allocation was made is invoked on the 
7735
 
** blob of allocated memory. This function should not call sqlite3_free()
 
8019
** blob of allocated memory. The xFree function should not call sqlite3_free()
7736
8020
** on the memory, the btree layer does that.
7737
8021
*/
7738
8022
void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
7739
8023
  BtShared *pBt = p->pBt;
7740
8024
  sqlite3BtreeEnter(p);
7741
8025
  if( !pBt->pSchema && nBytes ){
7742
 
    pBt->pSchema = sqlite3MallocZero(nBytes);
 
8026
    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
7743
8027
    pBt->xFreeSchema = xFree;
7744
8028
  }
7745
8029
  sqlite3BtreeLeave(p);
7844
8128
void sqlite3BtreeCacheOverflow(BtCursor *pCur){
7845
8129
  assert( cursorHoldsMutex(pCur) );
7846
8130
  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
7847
 
  assert(!pCur->isIncrblobHandle);
7848
 
  assert(!pCur->aOverflow);
 
8131
  invalidateOverflowCache(pCur);
7849
8132
  pCur->isIncrblobHandle = 1;
7850
8133
}
7851
8134
#endif
 
8135
 
 
8136
/*
 
8137
** Set both the "read version" (single byte at byte offset 18) and 
 
8138
** "write version" (single byte at byte offset 19) fields in the database
 
8139
** header to iVersion.
 
8140
*/
 
8141
int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
 
8142
  BtShared *pBt = pBtree->pBt;
 
8143
  int rc;                         /* Return code */
 
8144
 
 
8145
  assert( pBtree->inTrans==TRANS_NONE );
 
8146
  assert( iVersion==1 || iVersion==2 );
 
8147
 
 
8148
  /* If setting the version fields to 1, do not automatically open the
 
8149
  ** WAL connection, even if the version fields are currently set to 2.
 
8150
  */
 
8151
  pBt->doNotUseWAL = (u8)(iVersion==1);
 
8152
 
 
8153
  rc = sqlite3BtreeBeginTrans(pBtree, 0);
 
8154
  if( rc==SQLITE_OK ){
 
8155
    u8 *aData = pBt->pPage1->aData;
 
8156
    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
 
8157
      rc = sqlite3BtreeBeginTrans(pBtree, 2);
 
8158
      if( rc==SQLITE_OK ){
 
8159
        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
 
8160
        if( rc==SQLITE_OK ){
 
8161
          aData[18] = (u8)iVersion;
 
8162
          aData[19] = (u8)iVersion;
 
8163
        }
 
8164
      }
 
8165
    }
 
8166
  }
 
8167
 
 
8168
  pBt->doNotUseWAL = 0;
 
8169
  return rc;
 
8170
}