/ Check-in [a9bcb432]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Merge all of the latest trunk changes into the sessions branch.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sessions
Files: files | file ages | folders
SHA1: a9bcb432f58b96f079a73c456efd4851c582221e
User & Date: drh 2012-01-05 13:02:36
Context
2012-01-14
13:50
Update sessions branch with latest changes from trunk. check-in: 01c84fd3 user: dan tags: sessions
2012-01-05
13:02
Merge all of the latest trunk changes into the sessions branch. check-in: a9bcb432 user: drh tags: sessions
12:38
Ensure 8-byte alignment of Index.aiRowEst elements even if the size of an Index object is not a multiple of 8 bytes. check-in: 1378f905 user: drh tags: trunk
2011-10-31
14:34
Merge in all changes found in the version 3.7.9 release candidate. check-in: 23580718 user: drh tags: sessions
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to Makefile.in.

   514    514   	$(TCLSH_CMD) $(TOP)/tool/vdbe-compress.tcl <tsrc/vdbe.c >vdbe.new
   515    515   	mv vdbe.new tsrc/vdbe.c
   516    516   	touch .target_source
   517    517   
   518    518   sqlite3.c:	.target_source $(TOP)/tool/mksqlite3c.tcl
   519    519   	$(TCLSH_CMD) $(TOP)/tool/mksqlite3c.tcl
   520    520   
          521  +tclsqlite3.c:	sqlite3.c
          522  +	echo '#ifndef USE_SYSTEM_SQLITE' >tclsqlite3.c
          523  +	cat sqlite3.c >>tclsqlite3.c
          524  +	echo '#endif /* USE_SYSTEM_SQLITE */' >>tclsqlite3.c
          525  +	cat $(TOP)/src/tclsqlite.c >>tclsqlite3.c
          526  +
   521    527   sqlite3-all.c:	sqlite3.c $(TOP)/tool/split-sqlite3c.tcl
   522    528   	$(TCLSH_CMD) $(TOP)/tool/split-sqlite3c.tcl
   523    529   
   524    530   # Rule to build the amalgamation
   525    531   #
   526    532   sqlite3.lo:	sqlite3.c
   527    533   	$(LTCOMPILE) $(TEMP_STORE) -c sqlite3.c

Changes to VERSION.

     1         -3.7.9
            1  +3.7.10

Changes to config.h.in.

    28     28   #undef HAVE_INTTYPES_H
    29     29   
    30     30   /* Define to 1 if you have the `localtime_r' function. */
    31     31   #undef HAVE_LOCALTIME_R
    32     32   
    33     33   /* Define to 1 if you have the `localtime_s' function. */
    34     34   #undef HAVE_LOCALTIME_S
           35  +
           36  +/* Define to 1 if you have the `malloc_usable_size' function. */
           37  +#undef HAVE_MALLOC_USABLE_SIZE
    35     38   
    36     39   /* Define to 1 if you have the <memory.h> header file. */
    37     40   #undef HAVE_MEMORY_H
    38     41   
    39     42   /* Define to 1 if you have the <stdint.h> header file. */
    40     43   #undef HAVE_STDINT_H
    41     44   

Changes to configure.

     1      1   #! /bin/sh
     2      2   # Guess values for system-dependent variables and create Makefiles.
     3         -# Generated by GNU Autoconf 2.67 for sqlite 3.7.9.
            3  +# Generated by GNU Autoconf 2.68 for sqlite 3.7.10.
     4      4   #
     5      5   #
     6      6   # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
     7      7   # 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
     8      8   # Foundation, Inc.
     9      9   #
    10     10   #
................................................................................
    85     85   # We need space, tab and new line, in precisely that order.  Quoting is
    86     86   # there to prevent editors from complaining about space-tab.
    87     87   # (If _AS_PATH_WALK were called with IFS unset, it would disable word
    88     88   # splitting by setting IFS to empty value.)
    89     89   IFS=" ""	$as_nl"
    90     90   
    91     91   # Find who we are.  Look in the path if we contain no directory separator.
           92  +as_myself=
    92     93   case $0 in #((
    93     94     *[\\/]* ) as_myself=$0 ;;
    94     95     *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
    95     96   for as_dir in $PATH
    96     97   do
    97     98     IFS=$as_save_IFS
    98     99     test -z "$as_dir" && as_dir=.
................................................................................
   210    211   IFS=$as_save_IFS
   211    212   
   212    213   
   213    214         if test "x$CONFIG_SHELL" != x; then :
   214    215     # We cannot yet assume a decent shell, so we have to provide a
   215    216   	# neutralization value for shells without unset; and this also
   216    217   	# works around shells that cannot unset nonexistent variables.
          218  +	# Preserve -v and -x to the replacement shell.
   217    219   	BASH_ENV=/dev/null
   218    220   	ENV=/dev/null
   219    221   	(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
   220    222   	export CONFIG_SHELL
   221         -	exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
          223  +	case $- in # ((((
          224  +	  *v*x* | *x*v* ) as_opts=-vx ;;
          225  +	  *v* ) as_opts=-v ;;
          226  +	  *x* ) as_opts=-x ;;
          227  +	  * ) as_opts= ;;
          228  +	esac
          229  +	exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"}
   222    230   fi
   223    231   
   224    232       if test x$as_have_required = xno; then :
   225    233     $as_echo "$0: This script requires a shell more modern than all"
   226    234     $as_echo "$0: the shells that I found on your system."
   227    235     if test x${ZSH_VERSION+set} = xset ; then
   228    236       $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
................................................................................
   694    702   subdirs=
   695    703   MFLAGS=
   696    704   MAKEFLAGS=
   697    705   
   698    706   # Identity of this package.
   699    707   PACKAGE_NAME='sqlite'
   700    708   PACKAGE_TARNAME='sqlite'
   701         -PACKAGE_VERSION='3.7.9'
   702         -PACKAGE_STRING='sqlite 3.7.9'
          709  +PACKAGE_VERSION='3.7.10'
          710  +PACKAGE_STRING='sqlite 3.7.10'
   703    711   PACKAGE_BUGREPORT=''
   704    712   PACKAGE_URL=''
   705    713   
   706    714   # Factoring default headers for most tests.
   707    715   ac_includes_default="\
   708    716   #include <stdio.h>
   709    717   #ifdef HAVE_SYS_TYPES_H
................................................................................
  1290   1298       export $ac_envvar ;;
  1291   1299   
  1292   1300     *)
  1293   1301       # FIXME: should be removed in autoconf 3.0.
  1294   1302       $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
  1295   1303       expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
  1296   1304         $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
  1297         -    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
         1305  +    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
  1298   1306       ;;
  1299   1307   
  1300   1308     esac
  1301   1309   done
  1302   1310   
  1303   1311   if test -n "$ac_prev"; then
  1304   1312     ac_option=--`echo $ac_prev | sed 's/_/-/g'`
................................................................................
  1428   1436   #
  1429   1437   # Report the --help message.
  1430   1438   #
  1431   1439   if test "$ac_init_help" = "long"; then
  1432   1440     # Omit some internal or obsolete options to make the list less imposing.
  1433   1441     # This message is too long to be a string in the A/UX 3.1 sh.
  1434   1442     cat <<_ACEOF
  1435         -\`configure' configures sqlite 3.7.9 to adapt to many kinds of systems.
         1443  +\`configure' configures sqlite 3.7.10 to adapt to many kinds of systems.
  1436   1444   
  1437   1445   Usage: $0 [OPTION]... [VAR=VALUE]...
  1438   1446   
  1439   1447   To assign environment variables (e.g., CC, CFLAGS...), specify them as
  1440   1448   VAR=VALUE.  See below for descriptions of some of the useful variables.
  1441   1449   
  1442   1450   Defaults for the options are specified in brackets.
................................................................................
  1493   1501     --build=BUILD     configure for building on BUILD [guessed]
  1494   1502     --host=HOST       cross-compile to build programs to run on HOST [BUILD]
  1495   1503   _ACEOF
  1496   1504   fi
  1497   1505   
  1498   1506   if test -n "$ac_init_help"; then
  1499   1507     case $ac_init_help in
  1500         -     short | recursive ) echo "Configuration of sqlite 3.7.9:";;
         1508  +     short | recursive ) echo "Configuration of sqlite 3.7.10:";;
  1501   1509      esac
  1502   1510     cat <<\_ACEOF
  1503   1511   
  1504   1512   Optional Features:
  1505   1513     --disable-option-checking  ignore unrecognized --enable/--with options
  1506   1514     --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  1507   1515     --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
................................................................................
  1610   1618       cd "$ac_pwd" || { ac_status=$?; break; }
  1611   1619     done
  1612   1620   fi
  1613   1621   
  1614   1622   test -n "$ac_init_help" && exit $ac_status
  1615   1623   if $ac_init_version; then
  1616   1624     cat <<\_ACEOF
  1617         -sqlite configure 3.7.9
  1618         -generated by GNU Autoconf 2.67
         1625  +sqlite configure 3.7.10
         1626  +generated by GNU Autoconf 2.68
  1619   1627   
  1620   1628   Copyright (C) 2010 Free Software Foundation, Inc.
  1621   1629   This configure script is free software; the Free Software Foundation
  1622   1630   gives unlimited permission to copy, distribute and modify it.
  1623   1631   _ACEOF
  1624   1632     exit
  1625   1633   fi
................................................................................
  1657   1665     ac_retval=0
  1658   1666   else
  1659   1667     $as_echo "$as_me: failed program was:" >&5
  1660   1668   sed 's/^/| /' conftest.$ac_ext >&5
  1661   1669   
  1662   1670   	ac_retval=1
  1663   1671   fi
  1664         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         1672  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  1665   1673     as_fn_set_status $ac_retval
  1666   1674   
  1667   1675   } # ac_fn_c_try_compile
  1668   1676   
  1669   1677   # ac_fn_c_try_link LINENO
  1670   1678   # -----------------------
  1671   1679   # Try to link conftest.$ac_ext, and return whether this succeeded.
................................................................................
  1703   1711   	ac_retval=1
  1704   1712   fi
  1705   1713     # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information
  1706   1714     # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would
  1707   1715     # interfere with the next link command; also delete a directory that is
  1708   1716     # left behind by Apple's compiler.  We do this before executing the actions.
  1709   1717     rm -rf conftest.dSYM conftest_ipa8_conftest.oo
  1710         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         1718  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  1711   1719     as_fn_set_status $ac_retval
  1712   1720   
  1713   1721   } # ac_fn_c_try_link
  1714   1722   
  1715   1723   # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
  1716   1724   # -------------------------------------------------------
  1717   1725   # Tests whether HEADER exists and can be compiled using the include files in
  1718   1726   # INCLUDES, setting the cache variable VAR accordingly.
  1719   1727   ac_fn_c_check_header_compile ()
  1720   1728   {
  1721   1729     as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
  1722   1730     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
  1723   1731   $as_echo_n "checking for $2... " >&6; }
  1724         -if eval "test \"\${$3+set}\"" = set; then :
         1732  +if eval \${$3+:} false; then :
  1725   1733     $as_echo_n "(cached) " >&6
  1726   1734   else
  1727   1735     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  1728   1736   /* end confdefs.h.  */
  1729   1737   $4
  1730   1738   #include <$2>
  1731   1739   _ACEOF
................................................................................
  1735   1743     eval "$3=no"
  1736   1744   fi
  1737   1745   rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
  1738   1746   fi
  1739   1747   eval ac_res=\$$3
  1740   1748   	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
  1741   1749   $as_echo "$ac_res" >&6; }
  1742         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         1750  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  1743   1751   
  1744   1752   } # ac_fn_c_check_header_compile
  1745   1753   
  1746   1754   # ac_fn_c_try_cpp LINENO
  1747   1755   # ----------------------
  1748   1756   # Try to preprocess conftest.$ac_ext, and return whether this succeeded.
  1749   1757   ac_fn_c_try_cpp ()
................................................................................
  1771   1779     ac_retval=0
  1772   1780   else
  1773   1781     $as_echo "$as_me: failed program was:" >&5
  1774   1782   sed 's/^/| /' conftest.$ac_ext >&5
  1775   1783   
  1776   1784       ac_retval=1
  1777   1785   fi
  1778         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         1786  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  1779   1787     as_fn_set_status $ac_retval
  1780   1788   
  1781   1789   } # ac_fn_c_try_cpp
  1782   1790   
  1783   1791   # ac_fn_c_try_run LINENO
  1784   1792   # ----------------------
  1785   1793   # Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
................................................................................
  1813   1821     $as_echo "$as_me: program exited with status $ac_status" >&5
  1814   1822          $as_echo "$as_me: failed program was:" >&5
  1815   1823   sed 's/^/| /' conftest.$ac_ext >&5
  1816   1824   
  1817   1825          ac_retval=$ac_status
  1818   1826   fi
  1819   1827     rm -rf conftest.dSYM conftest_ipa8_conftest.oo
  1820         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         1828  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  1821   1829     as_fn_set_status $ac_retval
  1822   1830   
  1823   1831   } # ac_fn_c_try_run
  1824   1832   
  1825   1833   # ac_fn_c_check_func LINENO FUNC VAR
  1826   1834   # ----------------------------------
  1827   1835   # Tests whether FUNC exists, setting the cache variable VAR accordingly
  1828   1836   ac_fn_c_check_func ()
  1829   1837   {
  1830   1838     as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
  1831   1839     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
  1832   1840   $as_echo_n "checking for $2... " >&6; }
  1833         -if eval "test \"\${$3+set}\"" = set; then :
         1841  +if eval \${$3+:} false; then :
  1834   1842     $as_echo_n "(cached) " >&6
  1835   1843   else
  1836   1844     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  1837   1845   /* end confdefs.h.  */
  1838   1846   /* Define $2 to an innocuous variant, in case <limits.h> declares $2.
  1839   1847      For example, HP-UX 11i <limits.h> declares gettimeofday.  */
  1840   1848   #define $2 innocuous_$2
................................................................................
  1881   1889   fi
  1882   1890   rm -f core conftest.err conftest.$ac_objext \
  1883   1891       conftest$ac_exeext conftest.$ac_ext
  1884   1892   fi
  1885   1893   eval ac_res=\$$3
  1886   1894   	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
  1887   1895   $as_echo "$ac_res" >&6; }
  1888         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         1896  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  1889   1897   
  1890   1898   } # ac_fn_c_check_func
  1891   1899   
  1892   1900   # ac_fn_c_check_type LINENO TYPE VAR INCLUDES
  1893   1901   # -------------------------------------------
  1894   1902   # Tests whether TYPE exists after having included INCLUDES, setting cache
  1895   1903   # variable VAR accordingly.
  1896   1904   ac_fn_c_check_type ()
  1897   1905   {
  1898   1906     as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
  1899   1907     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
  1900   1908   $as_echo_n "checking for $2... " >&6; }
  1901         -if eval "test \"\${$3+set}\"" = set; then :
         1909  +if eval \${$3+:} false; then :
  1902   1910     $as_echo_n "(cached) " >&6
  1903   1911   else
  1904   1912     eval "$3=no"
  1905   1913     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  1906   1914   /* end confdefs.h.  */
  1907   1915   $4
  1908   1916   int
................................................................................
  1935   1943   rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
  1936   1944   fi
  1937   1945   rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
  1938   1946   fi
  1939   1947   eval ac_res=\$$3
  1940   1948   	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
  1941   1949   $as_echo "$ac_res" >&6; }
  1942         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         1950  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  1943   1951   
  1944   1952   } # ac_fn_c_check_type
  1945   1953   
  1946   1954   # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
  1947   1955   # -------------------------------------------------------
  1948   1956   # Tests whether HEADER exists, giving a warning if it cannot be compiled using
  1949   1957   # the include files in INCLUDES and setting the cache variable VAR
  1950   1958   # accordingly.
  1951   1959   ac_fn_c_check_header_mongrel ()
  1952   1960   {
  1953   1961     as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
  1954         -  if eval "test \"\${$3+set}\"" = set; then :
         1962  +  if eval \${$3+:} false; then :
  1955   1963     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
  1956   1964   $as_echo_n "checking for $2... " >&6; }
  1957         -if eval "test \"\${$3+set}\"" = set; then :
         1965  +if eval \${$3+:} false; then :
  1958   1966     $as_echo_n "(cached) " >&6
  1959   1967   fi
  1960   1968   eval ac_res=\$$3
  1961   1969   	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
  1962   1970   $as_echo "$ac_res" >&6; }
  1963   1971   else
  1964   1972     # Is the header compilable?
................................................................................
  2013   2021   $as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
  2014   2022       { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
  2015   2023   $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
  2016   2024       ;;
  2017   2025   esac
  2018   2026     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
  2019   2027   $as_echo_n "checking for $2... " >&6; }
  2020         -if eval "test \"\${$3+set}\"" = set; then :
         2028  +if eval \${$3+:} false; then :
  2021   2029     $as_echo_n "(cached) " >&6
  2022   2030   else
  2023   2031     eval "$3=\$ac_header_compiler"
  2024   2032   fi
  2025   2033   eval ac_res=\$$3
  2026   2034   	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
  2027   2035   $as_echo "$ac_res" >&6; }
  2028   2036   fi
  2029         -  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
         2037  +  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
  2030   2038   
  2031   2039   } # ac_fn_c_check_header_mongrel
  2032   2040   cat >config.log <<_ACEOF
  2033   2041   This file contains any messages produced by compilers while
  2034   2042   running configure, to aid debugging if configure makes a mistake.
  2035   2043   
  2036         -It was created by sqlite $as_me 3.7.9, which was
  2037         -generated by GNU Autoconf 2.67.  Invocation command line was
         2044  +It was created by sqlite $as_me 3.7.10, which was
         2045  +generated by GNU Autoconf 2.68.  Invocation command line was
  2038   2046   
  2039   2047     $ $0 $@
  2040   2048   
  2041   2049   _ACEOF
  2042   2050   exec 5>>config.log
  2043   2051   {
  2044   2052   cat <<_ASUNAME
................................................................................
  2288   2296       { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5
  2289   2297   $as_echo "$as_me: loading site script $ac_site_file" >&6;}
  2290   2298       sed 's/^/| /' "$ac_site_file" >&5
  2291   2299       . "$ac_site_file" \
  2292   2300         || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
  2293   2301   $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
  2294   2302   as_fn_error $? "failed to load site script $ac_site_file
  2295         -See \`config.log' for more details" "$LINENO" 5 ; }
         2303  +See \`config.log' for more details" "$LINENO" 5; }
  2296   2304     fi
  2297   2305   done
  2298   2306   
  2299   2307   if test -r "$cache_file"; then
  2300   2308     # Some versions of bash will fail to source /dev/null (special files
  2301   2309     # actually), so we avoid doing that.  DJGPP emulates it as a regular file.
  2302   2310     if test /dev/null != "$cache_file" && test -f "$cache_file"; then
................................................................................
  2452   2460   
  2453   2461   # Make sure we can run config.sub.
  2454   2462   $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 ||
  2455   2463     as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5
  2456   2464   
  2457   2465   { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5
  2458   2466   $as_echo_n "checking build system type... " >&6; }
  2459         -if test "${ac_cv_build+set}" = set; then :
         2467  +if ${ac_cv_build+:} false; then :
  2460   2468     $as_echo_n "(cached) " >&6
  2461   2469   else
  2462   2470     ac_build_alias=$build_alias
  2463   2471   test "x$ac_build_alias" = x &&
  2464   2472     ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"`
  2465   2473   test "x$ac_build_alias" = x &&
  2466   2474     as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5
................................................................................
  2468   2476     as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5
  2469   2477   
  2470   2478   fi
  2471   2479   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5
  2472   2480   $as_echo "$ac_cv_build" >&6; }
  2473   2481   case $ac_cv_build in
  2474   2482   *-*-*) ;;
  2475         -*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5 ;;
         2483  +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;;
  2476   2484   esac
  2477   2485   build=$ac_cv_build
  2478   2486   ac_save_IFS=$IFS; IFS='-'
  2479   2487   set x $ac_cv_build
  2480   2488   shift
  2481   2489   build_cpu=$1
  2482   2490   build_vendor=$2
................................................................................
  2486   2494   build_os=$*
  2487   2495   IFS=$ac_save_IFS
  2488   2496   case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac
  2489   2497   
  2490   2498   
  2491   2499   { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5
  2492   2500   $as_echo_n "checking host system type... " >&6; }
  2493         -if test "${ac_cv_host+set}" = set; then :
         2501  +if ${ac_cv_host+:} false; then :
  2494   2502     $as_echo_n "(cached) " >&6
  2495   2503   else
  2496   2504     if test "x$host_alias" = x; then
  2497   2505     ac_cv_host=$ac_cv_build
  2498   2506   else
  2499   2507     ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` ||
  2500   2508       as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5
................................................................................
  2501   2509   fi
  2502   2510   
  2503   2511   fi
  2504   2512   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5
  2505   2513   $as_echo "$ac_cv_host" >&6; }
  2506   2514   case $ac_cv_host in
  2507   2515   *-*-*) ;;
  2508         -*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5 ;;
         2516  +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;;
  2509   2517   esac
  2510   2518   host=$ac_cv_host
  2511   2519   ac_save_IFS=$IFS; IFS='-'
  2512   2520   set x $ac_cv_host
  2513   2521   shift
  2514   2522   host_cpu=$1
  2515   2523   host_vendor=$2
................................................................................
  2527   2535   ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
  2528   2536   ac_compiler_gnu=$ac_cv_c_compiler_gnu
  2529   2537   if test -n "$ac_tool_prefix"; then
  2530   2538     # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
  2531   2539   set dummy ${ac_tool_prefix}gcc; ac_word=$2
  2532   2540   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  2533   2541   $as_echo_n "checking for $ac_word... " >&6; }
  2534         -if test "${ac_cv_prog_CC+set}" = set; then :
         2542  +if ${ac_cv_prog_CC+:} false; then :
  2535   2543     $as_echo_n "(cached) " >&6
  2536   2544   else
  2537   2545     if test -n "$CC"; then
  2538   2546     ac_cv_prog_CC="$CC" # Let the user override the test.
  2539   2547   else
  2540   2548   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  2541   2549   for as_dir in $PATH
................................................................................
  2567   2575   fi
  2568   2576   if test -z "$ac_cv_prog_CC"; then
  2569   2577     ac_ct_CC=$CC
  2570   2578     # Extract the first word of "gcc", so it can be a program name with args.
  2571   2579   set dummy gcc; ac_word=$2
  2572   2580   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  2573   2581   $as_echo_n "checking for $ac_word... " >&6; }
  2574         -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
         2582  +if ${ac_cv_prog_ac_ct_CC+:} false; then :
  2575   2583     $as_echo_n "(cached) " >&6
  2576   2584   else
  2577   2585     if test -n "$ac_ct_CC"; then
  2578   2586     ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
  2579   2587   else
  2580   2588   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  2581   2589   for as_dir in $PATH
................................................................................
  2620   2628   
  2621   2629   if test -z "$CC"; then
  2622   2630             if test -n "$ac_tool_prefix"; then
  2623   2631       # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
  2624   2632   set dummy ${ac_tool_prefix}cc; ac_word=$2
  2625   2633   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  2626   2634   $as_echo_n "checking for $ac_word... " >&6; }
  2627         -if test "${ac_cv_prog_CC+set}" = set; then :
         2635  +if ${ac_cv_prog_CC+:} false; then :
  2628   2636     $as_echo_n "(cached) " >&6
  2629   2637   else
  2630   2638     if test -n "$CC"; then
  2631   2639     ac_cv_prog_CC="$CC" # Let the user override the test.
  2632   2640   else
  2633   2641   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  2634   2642   for as_dir in $PATH
................................................................................
  2660   2668     fi
  2661   2669   fi
  2662   2670   if test -z "$CC"; then
  2663   2671     # Extract the first word of "cc", so it can be a program name with args.
  2664   2672   set dummy cc; ac_word=$2
  2665   2673   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  2666   2674   $as_echo_n "checking for $ac_word... " >&6; }
  2667         -if test "${ac_cv_prog_CC+set}" = set; then :
         2675  +if ${ac_cv_prog_CC+:} false; then :
  2668   2676     $as_echo_n "(cached) " >&6
  2669   2677   else
  2670   2678     if test -n "$CC"; then
  2671   2679     ac_cv_prog_CC="$CC" # Let the user override the test.
  2672   2680   else
  2673   2681     ac_prog_rejected=no
  2674   2682   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
................................................................................
  2719   2727     if test -n "$ac_tool_prefix"; then
  2720   2728     for ac_prog in cl.exe
  2721   2729     do
  2722   2730       # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
  2723   2731   set dummy $ac_tool_prefix$ac_prog; ac_word=$2
  2724   2732   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  2725   2733   $as_echo_n "checking for $ac_word... " >&6; }
  2726         -if test "${ac_cv_prog_CC+set}" = set; then :
         2734  +if ${ac_cv_prog_CC+:} false; then :
  2727   2735     $as_echo_n "(cached) " >&6
  2728   2736   else
  2729   2737     if test -n "$CC"; then
  2730   2738     ac_cv_prog_CC="$CC" # Let the user override the test.
  2731   2739   else
  2732   2740   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  2733   2741   for as_dir in $PATH
................................................................................
  2763   2771     ac_ct_CC=$CC
  2764   2772     for ac_prog in cl.exe
  2765   2773   do
  2766   2774     # Extract the first word of "$ac_prog", so it can be a program name with args.
  2767   2775   set dummy $ac_prog; ac_word=$2
  2768   2776   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  2769   2777   $as_echo_n "checking for $ac_word... " >&6; }
  2770         -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
         2778  +if ${ac_cv_prog_ac_ct_CC+:} false; then :
  2771   2779     $as_echo_n "(cached) " >&6
  2772   2780   else
  2773   2781     if test -n "$ac_ct_CC"; then
  2774   2782     ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
  2775   2783   else
  2776   2784   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  2777   2785   for as_dir in $PATH
................................................................................
  2818   2826   
  2819   2827   fi
  2820   2828   
  2821   2829   
  2822   2830   test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
  2823   2831   $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
  2824   2832   as_fn_error $? "no acceptable C compiler found in \$PATH
  2825         -See \`config.log' for more details" "$LINENO" 5 ; }
         2833  +See \`config.log' for more details" "$LINENO" 5; }
  2826   2834   
  2827   2835   # Provide some information about the compiler.
  2828   2836   $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
  2829   2837   set X $ac_compile
  2830   2838   ac_compiler=$2
  2831   2839   for ac_option in --version -v -V -qversion; do
  2832   2840     { { ac_try="$ac_compiler $ac_option >&5"
................................................................................
  2933   2941   $as_echo "no" >&6; }
  2934   2942   $as_echo "$as_me: failed program was:" >&5
  2935   2943   sed 's/^/| /' conftest.$ac_ext >&5
  2936   2944   
  2937   2945   { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
  2938   2946   $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
  2939   2947   as_fn_error 77 "C compiler cannot create executables
  2940         -See \`config.log' for more details" "$LINENO" 5 ; }
         2948  +See \`config.log' for more details" "$LINENO" 5; }
  2941   2949   else
  2942   2950     { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
  2943   2951   $as_echo "yes" >&6; }
  2944   2952   fi
  2945   2953   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5
  2946   2954   $as_echo_n "checking for C compiler default output file name... " >&6; }
  2947   2955   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5
................................................................................
  2976   2984       * ) break;;
  2977   2985     esac
  2978   2986   done
  2979   2987   else
  2980   2988     { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
  2981   2989   $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
  2982   2990   as_fn_error $? "cannot compute suffix of executables: cannot compile and link
  2983         -See \`config.log' for more details" "$LINENO" 5 ; }
         2991  +See \`config.log' for more details" "$LINENO" 5; }
  2984   2992   fi
  2985   2993   rm -f conftest conftest$ac_cv_exeext
  2986   2994   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
  2987   2995   $as_echo "$ac_cv_exeext" >&6; }
  2988   2996   
  2989   2997   rm -f conftest.$ac_ext
  2990   2998   EXEEXT=$ac_cv_exeext
................................................................................
  3035   3043       if test "$cross_compiling" = maybe; then
  3036   3044   	cross_compiling=yes
  3037   3045       else
  3038   3046   	{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
  3039   3047   $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
  3040   3048   as_fn_error $? "cannot run C compiled programs.
  3041   3049   If you meant to cross compile, use \`--host'.
  3042         -See \`config.log' for more details" "$LINENO" 5 ; }
         3050  +See \`config.log' for more details" "$LINENO" 5; }
  3043   3051       fi
  3044   3052     fi
  3045   3053   fi
  3046   3054   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5
  3047   3055   $as_echo "$cross_compiling" >&6; }
  3048   3056   
  3049   3057   rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
  3050   3058   ac_clean_files=$ac_clean_files_save
  3051   3059   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
  3052   3060   $as_echo_n "checking for suffix of object files... " >&6; }
  3053         -if test "${ac_cv_objext+set}" = set; then :
         3061  +if ${ac_cv_objext+:} false; then :
  3054   3062     $as_echo_n "(cached) " >&6
  3055   3063   else
  3056   3064     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  3057   3065   /* end confdefs.h.  */
  3058   3066   
  3059   3067   int
  3060   3068   main ()
................................................................................
  3087   3095   else
  3088   3096     $as_echo "$as_me: failed program was:" >&5
  3089   3097   sed 's/^/| /' conftest.$ac_ext >&5
  3090   3098   
  3091   3099   { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
  3092   3100   $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
  3093   3101   as_fn_error $? "cannot compute suffix of object files: cannot compile
  3094         -See \`config.log' for more details" "$LINENO" 5 ; }
         3102  +See \`config.log' for more details" "$LINENO" 5; }
  3095   3103   fi
  3096   3104   rm -f conftest.$ac_cv_objext conftest.$ac_ext
  3097   3105   fi
  3098   3106   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5
  3099   3107   $as_echo "$ac_cv_objext" >&6; }
  3100   3108   OBJEXT=$ac_cv_objext
  3101   3109   ac_objext=$OBJEXT
  3102   3110   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
  3103   3111   $as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
  3104         -if test "${ac_cv_c_compiler_gnu+set}" = set; then :
         3112  +if ${ac_cv_c_compiler_gnu+:} false; then :
  3105   3113     $as_echo_n "(cached) " >&6
  3106   3114   else
  3107   3115     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  3108   3116   /* end confdefs.h.  */
  3109   3117   
  3110   3118   int
  3111   3119   main ()
................................................................................
  3134   3142   else
  3135   3143     GCC=
  3136   3144   fi
  3137   3145   ac_test_CFLAGS=${CFLAGS+set}
  3138   3146   ac_save_CFLAGS=$CFLAGS
  3139   3147   { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
  3140   3148   $as_echo_n "checking whether $CC accepts -g... " >&6; }
  3141         -if test "${ac_cv_prog_cc_g+set}" = set; then :
         3149  +if ${ac_cv_prog_cc_g+:} false; then :
  3142   3150     $as_echo_n "(cached) " >&6
  3143   3151   else
  3144   3152     ac_save_c_werror_flag=$ac_c_werror_flag
  3145   3153      ac_c_werror_flag=yes
  3146   3154      ac_cv_prog_cc_g=no
  3147   3155      CFLAGS="-g"
  3148   3156      cat confdefs.h - <<_ACEOF >conftest.$ac_ext
................................................................................
  3212   3220       CFLAGS="-O2"
  3213   3221     else
  3214   3222       CFLAGS=
  3215   3223     fi
  3216   3224   fi
  3217   3225   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
  3218   3226   $as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
  3219         -if test "${ac_cv_prog_cc_c89+set}" = set; then :
         3227  +if ${ac_cv_prog_cc_c89+:} false; then :
  3220   3228     $as_echo_n "(cached) " >&6
  3221   3229   else
  3222   3230     ac_cv_prog_cc_c89=no
  3223   3231   ac_save_CC=$CC
  3224   3232   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  3225   3233   /* end confdefs.h.  */
  3226   3234   #include <stdarg.h>
................................................................................
  3309   3317   ac_cpp='$CPP $CPPFLAGS'
  3310   3318   ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
  3311   3319   ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
  3312   3320   ac_compiler_gnu=$ac_cv_c_compiler_gnu
  3313   3321   
  3314   3322   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5
  3315   3323   $as_echo_n "checking for a sed that does not truncate output... " >&6; }
  3316         -if test "${ac_cv_path_SED+set}" = set; then :
         3324  +if ${ac_cv_path_SED+:} false; then :
  3317   3325     $as_echo_n "(cached) " >&6
  3318   3326   else
  3319   3327               ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/
  3320   3328        for ac_i in 1 2 3 4 5 6 7; do
  3321   3329          ac_script="$ac_script$as_nl$ac_script"
  3322   3330        done
  3323   3331        echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed
................................................................................
  3391   3399   
  3392   3400   
  3393   3401   
  3394   3402   
  3395   3403   
  3396   3404   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
  3397   3405   $as_echo_n "checking for grep that handles long lines and -e... " >&6; }
  3398         -if test "${ac_cv_path_GREP+set}" = set; then :
         3406  +if ${ac_cv_path_GREP+:} false; then :
  3399   3407     $as_echo_n "(cached) " >&6
  3400   3408   else
  3401   3409     if test -z "$GREP"; then
  3402   3410     ac_path_GREP_found=false
  3403   3411     # Loop through the user's path and test for each of PROGNAME-LIST
  3404   3412     as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  3405   3413   for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
................................................................................
  3454   3462   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5
  3455   3463   $as_echo "$ac_cv_path_GREP" >&6; }
  3456   3464    GREP="$ac_cv_path_GREP"
  3457   3465   
  3458   3466   
  3459   3467   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
  3460   3468   $as_echo_n "checking for egrep... " >&6; }
  3461         -if test "${ac_cv_path_EGREP+set}" = set; then :
         3469  +if ${ac_cv_path_EGREP+:} false; then :
  3462   3470     $as_echo_n "(cached) " >&6
  3463   3471   else
  3464   3472     if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
  3465   3473      then ac_cv_path_EGREP="$GREP -E"
  3466   3474      else
  3467   3475        if test -z "$EGREP"; then
  3468   3476     ac_path_EGREP_found=false
................................................................................
  3521   3529   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5
  3522   3530   $as_echo "$ac_cv_path_EGREP" >&6; }
  3523   3531    EGREP="$ac_cv_path_EGREP"
  3524   3532   
  3525   3533   
  3526   3534   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5
  3527   3535   $as_echo_n "checking for fgrep... " >&6; }
  3528         -if test "${ac_cv_path_FGREP+set}" = set; then :
         3536  +if ${ac_cv_path_FGREP+:} false; then :
  3529   3537     $as_echo_n "(cached) " >&6
  3530   3538   else
  3531   3539     if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1
  3532   3540      then ac_cv_path_FGREP="$GREP -F"
  3533   3541      else
  3534   3542        if test -z "$FGREP"; then
  3535   3543     ac_path_FGREP_found=false
................................................................................
  3652   3660   elif test "$with_gnu_ld" = yes; then
  3653   3661     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU ld" >&5
  3654   3662   $as_echo_n "checking for GNU ld... " >&6; }
  3655   3663   else
  3656   3664     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for non-GNU ld" >&5
  3657   3665   $as_echo_n "checking for non-GNU ld... " >&6; }
  3658   3666   fi
  3659         -if test "${lt_cv_path_LD+set}" = set; then :
         3667  +if ${lt_cv_path_LD+:} false; then :
  3660   3668     $as_echo_n "(cached) " >&6
  3661   3669   else
  3662   3670     if test -z "$LD"; then
  3663   3671     lt_save_ifs="$IFS"; IFS=$PATH_SEPARATOR
  3664   3672     for ac_dir in $PATH; do
  3665   3673       IFS="$lt_save_ifs"
  3666   3674       test -z "$ac_dir" && ac_dir=.
................................................................................
  3692   3700   else
  3693   3701     { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5
  3694   3702   $as_echo "no" >&6; }
  3695   3703   fi
  3696   3704   test -z "$LD" && as_fn_error $? "no acceptable ld found in \$PATH" "$LINENO" 5
  3697   3705   { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the linker ($LD) is GNU ld" >&5
  3698   3706   $as_echo_n "checking if the linker ($LD) is GNU ld... " >&6; }
  3699         -if test "${lt_cv_prog_gnu_ld+set}" = set; then :
         3707  +if ${lt_cv_prog_gnu_ld+:} false; then :
  3700   3708     $as_echo_n "(cached) " >&6
  3701   3709   else
  3702   3710     # I'd rather use --version here, but apparently some GNU lds only accept -v.
  3703   3711   case `$LD -v 2>&1 </dev/null` in
  3704   3712   *GNU* | *'with BFD'*)
  3705   3713     lt_cv_prog_gnu_ld=yes
  3706   3714     ;;
................................................................................
  3719   3727   
  3720   3728   
  3721   3729   
  3722   3730   
  3723   3731   
  3724   3732   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for BSD- or MS-compatible name lister (nm)" >&5
  3725   3733   $as_echo_n "checking for BSD- or MS-compatible name lister (nm)... " >&6; }
  3726         -if test "${lt_cv_path_NM+set}" = set; then :
         3734  +if ${lt_cv_path_NM+:} false; then :
  3727   3735     $as_echo_n "(cached) " >&6
  3728   3736   else
  3729   3737     if test -n "$NM"; then
  3730   3738     # Let the user override the test.
  3731   3739     lt_cv_path_NM="$NM"
  3732   3740   else
  3733   3741     lt_nm_to_check="${ac_tool_prefix}nm"
................................................................................
  3779   3787     if test -n "$ac_tool_prefix"; then
  3780   3788     for ac_prog in "dumpbin -symbols" "link -dump -symbols"
  3781   3789     do
  3782   3790       # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
  3783   3791   set dummy $ac_tool_prefix$ac_prog; ac_word=$2
  3784   3792   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  3785   3793   $as_echo_n "checking for $ac_word... " >&6; }
  3786         -if test "${ac_cv_prog_DUMPBIN+set}" = set; then :
         3794  +if ${ac_cv_prog_DUMPBIN+:} false; then :
  3787   3795     $as_echo_n "(cached) " >&6
  3788   3796   else
  3789   3797     if test -n "$DUMPBIN"; then
  3790   3798     ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test.
  3791   3799   else
  3792   3800   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  3793   3801   for as_dir in $PATH
................................................................................
  3823   3831     ac_ct_DUMPBIN=$DUMPBIN
  3824   3832     for ac_prog in "dumpbin -symbols" "link -dump -symbols"
  3825   3833   do
  3826   3834     # Extract the first word of "$ac_prog", so it can be a program name with args.
  3827   3835   set dummy $ac_prog; ac_word=$2
  3828   3836   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  3829   3837   $as_echo_n "checking for $ac_word... " >&6; }
  3830         -if test "${ac_cv_prog_ac_ct_DUMPBIN+set}" = set; then :
         3838  +if ${ac_cv_prog_ac_ct_DUMPBIN+:} false; then :
  3831   3839     $as_echo_n "(cached) " >&6
  3832   3840   else
  3833   3841     if test -n "$ac_ct_DUMPBIN"; then
  3834   3842     ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test.
  3835   3843   else
  3836   3844   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  3837   3845   for as_dir in $PATH
................................................................................
  3886   3894   
  3887   3895   
  3888   3896   
  3889   3897   
  3890   3898   
  3891   3899   { $as_echo "$as_me:${as_lineno-$LINENO}: checking the name lister ($NM) interface" >&5
  3892   3900   $as_echo_n "checking the name lister ($NM) interface... " >&6; }
  3893         -if test "${lt_cv_nm_interface+set}" = set; then :
         3901  +if ${lt_cv_nm_interface+:} false; then :
  3894   3902     $as_echo_n "(cached) " >&6
  3895   3903   else
  3896   3904     lt_cv_nm_interface="BSD nm"
  3897   3905     echo "int some_variable = 0;" > conftest.$ac_ext
  3898         -  (eval echo "\"\$as_me:3898: $ac_compile\"" >&5)
         3906  +  (eval echo "\"\$as_me:3906: $ac_compile\"" >&5)
  3899   3907     (eval "$ac_compile" 2>conftest.err)
  3900   3908     cat conftest.err >&5
  3901         -  (eval echo "\"\$as_me:3901: $NM \\\"conftest.$ac_objext\\\"\"" >&5)
         3909  +  (eval echo "\"\$as_me:3909: $NM \\\"conftest.$ac_objext\\\"\"" >&5)
  3902   3910     (eval "$NM \"conftest.$ac_objext\"" 2>conftest.err > conftest.out)
  3903   3911     cat conftest.err >&5
  3904         -  (eval echo "\"\$as_me:3904: output\"" >&5)
         3912  +  (eval echo "\"\$as_me:3912: output\"" >&5)
  3905   3913     cat conftest.out >&5
  3906   3914     if $GREP 'External.*some_variable' conftest.out > /dev/null; then
  3907   3915       lt_cv_nm_interface="MS dumpbin"
  3908   3916     fi
  3909   3917     rm -f conftest*
  3910   3918   fi
  3911   3919   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5
................................................................................
  3921   3929     { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5
  3922   3930   $as_echo "no, using $LN_S" >&6; }
  3923   3931   fi
  3924   3932   
  3925   3933   # find the maximum length of command line arguments
  3926   3934   { $as_echo "$as_me:${as_lineno-$LINENO}: checking the maximum length of command line arguments" >&5
  3927   3935   $as_echo_n "checking the maximum length of command line arguments... " >&6; }
  3928         -if test "${lt_cv_sys_max_cmd_len+set}" = set; then :
         3936  +if ${lt_cv_sys_max_cmd_len+:} false; then :
  3929   3937     $as_echo_n "(cached) " >&6
  3930   3938   else
  3931   3939       i=0
  3932   3940     teststring="ABCD"
  3933   3941   
  3934   3942     case $build_os in
  3935   3943     msdosdjgpp*)
................................................................................
  4113   4121   
  4114   4122   
  4115   4123   
  4116   4124   
  4117   4125   
  4118   4126   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $LD option to reload object files" >&5
  4119   4127   $as_echo_n "checking for $LD option to reload object files... " >&6; }
  4120         -if test "${lt_cv_ld_reload_flag+set}" = set; then :
         4128  +if ${lt_cv_ld_reload_flag+:} false; then :
  4121   4129     $as_echo_n "(cached) " >&6
  4122   4130   else
  4123   4131     lt_cv_ld_reload_flag='-r'
  4124   4132   fi
  4125   4133   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5
  4126   4134   $as_echo "$lt_cv_ld_reload_flag" >&6; }
  4127   4135   reload_flag=$lt_cv_ld_reload_flag
................................................................................
  4149   4157   
  4150   4158   
  4151   4159   if test -n "$ac_tool_prefix"; then
  4152   4160     # Extract the first word of "${ac_tool_prefix}objdump", so it can be a program name with args.
  4153   4161   set dummy ${ac_tool_prefix}objdump; ac_word=$2
  4154   4162   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4155   4163   $as_echo_n "checking for $ac_word... " >&6; }
  4156         -if test "${ac_cv_prog_OBJDUMP+set}" = set; then :
         4164  +if ${ac_cv_prog_OBJDUMP+:} false; then :
  4157   4165     $as_echo_n "(cached) " >&6
  4158   4166   else
  4159   4167     if test -n "$OBJDUMP"; then
  4160   4168     ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test.
  4161   4169   else
  4162   4170   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4163   4171   for as_dir in $PATH
................................................................................
  4189   4197   fi
  4190   4198   if test -z "$ac_cv_prog_OBJDUMP"; then
  4191   4199     ac_ct_OBJDUMP=$OBJDUMP
  4192   4200     # Extract the first word of "objdump", so it can be a program name with args.
  4193   4201   set dummy objdump; ac_word=$2
  4194   4202   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4195   4203   $as_echo_n "checking for $ac_word... " >&6; }
  4196         -if test "${ac_cv_prog_ac_ct_OBJDUMP+set}" = set; then :
         4204  +if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then :
  4197   4205     $as_echo_n "(cached) " >&6
  4198   4206   else
  4199   4207     if test -n "$ac_ct_OBJDUMP"; then
  4200   4208     ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test.
  4201   4209   else
  4202   4210   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4203   4211   for as_dir in $PATH
................................................................................
  4248   4256   
  4249   4257   
  4250   4258   
  4251   4259   
  4252   4260   
  4253   4261   { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to recognize dependent libraries" >&5
  4254   4262   $as_echo_n "checking how to recognize dependent libraries... " >&6; }
  4255         -if test "${lt_cv_deplibs_check_method+set}" = set; then :
         4263  +if ${lt_cv_deplibs_check_method+:} false; then :
  4256   4264     $as_echo_n "(cached) " >&6
  4257   4265   else
  4258   4266     lt_cv_file_magic_cmd='$MAGIC_CMD'
  4259   4267   lt_cv_file_magic_test_file=
  4260   4268   lt_cv_deplibs_check_method='unknown'
  4261   4269   # Need to set the preceding variable on all platforms that support
  4262   4270   # interlibrary dependencies.
................................................................................
  4464   4472   
  4465   4473   
  4466   4474   if test -n "$ac_tool_prefix"; then
  4467   4475     # Extract the first word of "${ac_tool_prefix}ar", so it can be a program name with args.
  4468   4476   set dummy ${ac_tool_prefix}ar; ac_word=$2
  4469   4477   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4470   4478   $as_echo_n "checking for $ac_word... " >&6; }
  4471         -if test "${ac_cv_prog_AR+set}" = set; then :
         4479  +if ${ac_cv_prog_AR+:} false; then :
  4472   4480     $as_echo_n "(cached) " >&6
  4473   4481   else
  4474   4482     if test -n "$AR"; then
  4475   4483     ac_cv_prog_AR="$AR" # Let the user override the test.
  4476   4484   else
  4477   4485   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4478   4486   for as_dir in $PATH
................................................................................
  4504   4512   fi
  4505   4513   if test -z "$ac_cv_prog_AR"; then
  4506   4514     ac_ct_AR=$AR
  4507   4515     # Extract the first word of "ar", so it can be a program name with args.
  4508   4516   set dummy ar; ac_word=$2
  4509   4517   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4510   4518   $as_echo_n "checking for $ac_word... " >&6; }
  4511         -if test "${ac_cv_prog_ac_ct_AR+set}" = set; then :
         4519  +if ${ac_cv_prog_ac_ct_AR+:} false; then :
  4512   4520     $as_echo_n "(cached) " >&6
  4513   4521   else
  4514   4522     if test -n "$ac_ct_AR"; then
  4515   4523     ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test.
  4516   4524   else
  4517   4525   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4518   4526   for as_dir in $PATH
................................................................................
  4569   4577   
  4570   4578   
  4571   4579   if test -n "$ac_tool_prefix"; then
  4572   4580     # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
  4573   4581   set dummy ${ac_tool_prefix}strip; ac_word=$2
  4574   4582   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4575   4583   $as_echo_n "checking for $ac_word... " >&6; }
  4576         -if test "${ac_cv_prog_STRIP+set}" = set; then :
         4584  +if ${ac_cv_prog_STRIP+:} false; then :
  4577   4585     $as_echo_n "(cached) " >&6
  4578   4586   else
  4579   4587     if test -n "$STRIP"; then
  4580   4588     ac_cv_prog_STRIP="$STRIP" # Let the user override the test.
  4581   4589   else
  4582   4590   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4583   4591   for as_dir in $PATH
................................................................................
  4609   4617   fi
  4610   4618   if test -z "$ac_cv_prog_STRIP"; then
  4611   4619     ac_ct_STRIP=$STRIP
  4612   4620     # Extract the first word of "strip", so it can be a program name with args.
  4613   4621   set dummy strip; ac_word=$2
  4614   4622   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4615   4623   $as_echo_n "checking for $ac_word... " >&6; }
  4616         -if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then :
         4624  +if ${ac_cv_prog_ac_ct_STRIP+:} false; then :
  4617   4625     $as_echo_n "(cached) " >&6
  4618   4626   else
  4619   4627     if test -n "$ac_ct_STRIP"; then
  4620   4628     ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test.
  4621   4629   else
  4622   4630   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4623   4631   for as_dir in $PATH
................................................................................
  4668   4676   
  4669   4677   
  4670   4678   if test -n "$ac_tool_prefix"; then
  4671   4679     # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args.
  4672   4680   set dummy ${ac_tool_prefix}ranlib; ac_word=$2
  4673   4681   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4674   4682   $as_echo_n "checking for $ac_word... " >&6; }
  4675         -if test "${ac_cv_prog_RANLIB+set}" = set; then :
         4683  +if ${ac_cv_prog_RANLIB+:} false; then :
  4676   4684     $as_echo_n "(cached) " >&6
  4677   4685   else
  4678   4686     if test -n "$RANLIB"; then
  4679   4687     ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test.
  4680   4688   else
  4681   4689   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4682   4690   for as_dir in $PATH
................................................................................
  4708   4716   fi
  4709   4717   if test -z "$ac_cv_prog_RANLIB"; then
  4710   4718     ac_ct_RANLIB=$RANLIB
  4711   4719     # Extract the first word of "ranlib", so it can be a program name with args.
  4712   4720   set dummy ranlib; ac_word=$2
  4713   4721   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  4714   4722   $as_echo_n "checking for $ac_word... " >&6; }
  4715         -if test "${ac_cv_prog_ac_ct_RANLIB+set}" = set; then :
         4723  +if ${ac_cv_prog_ac_ct_RANLIB+:} false; then :
  4716   4724     $as_echo_n "(cached) " >&6
  4717   4725   else
  4718   4726     if test -n "$ac_ct_RANLIB"; then
  4719   4727     ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test.
  4720   4728   else
  4721   4729   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  4722   4730   for as_dir in $PATH
................................................................................
  4825   4833   # Allow CC to be a program name with arguments.
  4826   4834   compiler=$CC
  4827   4835   
  4828   4836   
  4829   4837   # Check for command to grab the raw symbol name followed by C symbol from nm.
  4830   4838   { $as_echo "$as_me:${as_lineno-$LINENO}: checking command to parse $NM output from $compiler object" >&5
  4831   4839   $as_echo_n "checking command to parse $NM output from $compiler object... " >&6; }
  4832         -if test "${lt_cv_sys_global_symbol_pipe+set}" = set; then :
         4840  +if ${lt_cv_sys_global_symbol_pipe+:} false; then :
  4833   4841     $as_echo_n "(cached) " >&6
  4834   4842   else
  4835   4843   
  4836   4844   # These are sane defaults that work on at least a few old systems.
  4837   4845   # [They come from Ultrix.  What could be older than Ultrix?!! ;)]
  4838   4846   
  4839   4847   # Character class describing NM global symbol codes.
................................................................................
  5103   5111   	;;
  5104   5112       esac
  5105   5113     fi
  5106   5114     rm -rf conftest*
  5107   5115     ;;
  5108   5116   *-*-irix6*)
  5109   5117     # Find out which ABI we are using.
  5110         -  echo '#line 5110 "configure"' > conftest.$ac_ext
         5118  +  echo '#line 5118 "configure"' > conftest.$ac_ext
  5111   5119     if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5
  5112   5120     (eval $ac_compile) 2>&5
  5113   5121     ac_status=$?
  5114   5122     $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
  5115   5123     test $ac_status = 0; }; then
  5116   5124       if test "$lt_cv_prog_gnu_ld" = yes; then
  5117   5125         case `/usr/bin/file conftest.$ac_objext` in
................................................................................
  5197   5205   
  5198   5206   *-*-sco3.2v5*)
  5199   5207     # On SCO OpenServer 5, we need -belf to get full-featured binaries.
  5200   5208     SAVE_CFLAGS="$CFLAGS"
  5201   5209     CFLAGS="$CFLAGS -belf"
  5202   5210     { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler needs -belf" >&5
  5203   5211   $as_echo_n "checking whether the C compiler needs -belf... " >&6; }
  5204         -if test "${lt_cv_cc_needs_belf+set}" = set; then :
         5212  +if ${lt_cv_cc_needs_belf+:} false; then :
  5205   5213     $as_echo_n "(cached) " >&6
  5206   5214   else
  5207   5215     ac_ext=c
  5208   5216   ac_cpp='$CPP $CPPFLAGS'
  5209   5217   ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
  5210   5218   ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
  5211   5219   ac_compiler_gnu=$ac_cv_c_compiler_gnu
................................................................................
  5273   5281     case $host_os in
  5274   5282       rhapsody* | darwin*)
  5275   5283       if test -n "$ac_tool_prefix"; then
  5276   5284     # Extract the first word of "${ac_tool_prefix}dsymutil", so it can be a program name with args.
  5277   5285   set dummy ${ac_tool_prefix}dsymutil; ac_word=$2
  5278   5286   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5279   5287   $as_echo_n "checking for $ac_word... " >&6; }
  5280         -if test "${ac_cv_prog_DSYMUTIL+set}" = set; then :
         5288  +if ${ac_cv_prog_DSYMUTIL+:} false; then :
  5281   5289     $as_echo_n "(cached) " >&6
  5282   5290   else
  5283   5291     if test -n "$DSYMUTIL"; then
  5284   5292     ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test.
  5285   5293   else
  5286   5294   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5287   5295   for as_dir in $PATH
................................................................................
  5313   5321   fi
  5314   5322   if test -z "$ac_cv_prog_DSYMUTIL"; then
  5315   5323     ac_ct_DSYMUTIL=$DSYMUTIL
  5316   5324     # Extract the first word of "dsymutil", so it can be a program name with args.
  5317   5325   set dummy dsymutil; ac_word=$2
  5318   5326   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5319   5327   $as_echo_n "checking for $ac_word... " >&6; }
  5320         -if test "${ac_cv_prog_ac_ct_DSYMUTIL+set}" = set; then :
         5328  +if ${ac_cv_prog_ac_ct_DSYMUTIL+:} false; then :
  5321   5329     $as_echo_n "(cached) " >&6
  5322   5330   else
  5323   5331     if test -n "$ac_ct_DSYMUTIL"; then
  5324   5332     ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test.
  5325   5333   else
  5326   5334   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5327   5335   for as_dir in $PATH
................................................................................
  5365   5373   fi
  5366   5374   
  5367   5375       if test -n "$ac_tool_prefix"; then
  5368   5376     # Extract the first word of "${ac_tool_prefix}nmedit", so it can be a program name with args.
  5369   5377   set dummy ${ac_tool_prefix}nmedit; ac_word=$2
  5370   5378   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5371   5379   $as_echo_n "checking for $ac_word... " >&6; }
  5372         -if test "${ac_cv_prog_NMEDIT+set}" = set; then :
         5380  +if ${ac_cv_prog_NMEDIT+:} false; then :
  5373   5381     $as_echo_n "(cached) " >&6
  5374   5382   else
  5375   5383     if test -n "$NMEDIT"; then
  5376   5384     ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test.
  5377   5385   else
  5378   5386   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5379   5387   for as_dir in $PATH
................................................................................
  5405   5413   fi
  5406   5414   if test -z "$ac_cv_prog_NMEDIT"; then
  5407   5415     ac_ct_NMEDIT=$NMEDIT
  5408   5416     # Extract the first word of "nmedit", so it can be a program name with args.
  5409   5417   set dummy nmedit; ac_word=$2
  5410   5418   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5411   5419   $as_echo_n "checking for $ac_word... " >&6; }
  5412         -if test "${ac_cv_prog_ac_ct_NMEDIT+set}" = set; then :
         5420  +if ${ac_cv_prog_ac_ct_NMEDIT+:} false; then :
  5413   5421     $as_echo_n "(cached) " >&6
  5414   5422   else
  5415   5423     if test -n "$ac_ct_NMEDIT"; then
  5416   5424     ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test.
  5417   5425   else
  5418   5426   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5419   5427   for as_dir in $PATH
................................................................................
  5457   5465   fi
  5458   5466   
  5459   5467       if test -n "$ac_tool_prefix"; then
  5460   5468     # Extract the first word of "${ac_tool_prefix}lipo", so it can be a program name with args.
  5461   5469   set dummy ${ac_tool_prefix}lipo; ac_word=$2
  5462   5470   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5463   5471   $as_echo_n "checking for $ac_word... " >&6; }
  5464         -if test "${ac_cv_prog_LIPO+set}" = set; then :
         5472  +if ${ac_cv_prog_LIPO+:} false; then :
  5465   5473     $as_echo_n "(cached) " >&6
  5466   5474   else
  5467   5475     if test -n "$LIPO"; then
  5468   5476     ac_cv_prog_LIPO="$LIPO" # Let the user override the test.
  5469   5477   else
  5470   5478   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5471   5479   for as_dir in $PATH
................................................................................
  5497   5505   fi
  5498   5506   if test -z "$ac_cv_prog_LIPO"; then
  5499   5507     ac_ct_LIPO=$LIPO
  5500   5508     # Extract the first word of "lipo", so it can be a program name with args.
  5501   5509   set dummy lipo; ac_word=$2
  5502   5510   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5503   5511   $as_echo_n "checking for $ac_word... " >&6; }
  5504         -if test "${ac_cv_prog_ac_ct_LIPO+set}" = set; then :
         5512  +if ${ac_cv_prog_ac_ct_LIPO+:} false; then :
  5505   5513     $as_echo_n "(cached) " >&6
  5506   5514   else
  5507   5515     if test -n "$ac_ct_LIPO"; then
  5508   5516     ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test.
  5509   5517   else
  5510   5518   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5511   5519   for as_dir in $PATH
................................................................................
  5549   5557   fi
  5550   5558   
  5551   5559       if test -n "$ac_tool_prefix"; then
  5552   5560     # Extract the first word of "${ac_tool_prefix}otool", so it can be a program name with args.
  5553   5561   set dummy ${ac_tool_prefix}otool; ac_word=$2
  5554   5562   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5555   5563   $as_echo_n "checking for $ac_word... " >&6; }
  5556         -if test "${ac_cv_prog_OTOOL+set}" = set; then :
         5564  +if ${ac_cv_prog_OTOOL+:} false; then :
  5557   5565     $as_echo_n "(cached) " >&6
  5558   5566   else
  5559   5567     if test -n "$OTOOL"; then
  5560   5568     ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test.
  5561   5569   else
  5562   5570   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5563   5571   for as_dir in $PATH
................................................................................
  5589   5597   fi
  5590   5598   if test -z "$ac_cv_prog_OTOOL"; then
  5591   5599     ac_ct_OTOOL=$OTOOL
  5592   5600     # Extract the first word of "otool", so it can be a program name with args.
  5593   5601   set dummy otool; ac_word=$2
  5594   5602   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5595   5603   $as_echo_n "checking for $ac_word... " >&6; }
  5596         -if test "${ac_cv_prog_ac_ct_OTOOL+set}" = set; then :
         5604  +if ${ac_cv_prog_ac_ct_OTOOL+:} false; then :
  5597   5605     $as_echo_n "(cached) " >&6
  5598   5606   else
  5599   5607     if test -n "$ac_ct_OTOOL"; then
  5600   5608     ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test.
  5601   5609   else
  5602   5610   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5603   5611   for as_dir in $PATH
................................................................................
  5641   5649   fi
  5642   5650   
  5643   5651       if test -n "$ac_tool_prefix"; then
  5644   5652     # Extract the first word of "${ac_tool_prefix}otool64", so it can be a program name with args.
  5645   5653   set dummy ${ac_tool_prefix}otool64; ac_word=$2
  5646   5654   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5647   5655   $as_echo_n "checking for $ac_word... " >&6; }
  5648         -if test "${ac_cv_prog_OTOOL64+set}" = set; then :
         5656  +if ${ac_cv_prog_OTOOL64+:} false; then :
  5649   5657     $as_echo_n "(cached) " >&6
  5650   5658   else
  5651   5659     if test -n "$OTOOL64"; then
  5652   5660     ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test.
  5653   5661   else
  5654   5662   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5655   5663   for as_dir in $PATH
................................................................................
  5681   5689   fi
  5682   5690   if test -z "$ac_cv_prog_OTOOL64"; then
  5683   5691     ac_ct_OTOOL64=$OTOOL64
  5684   5692     # Extract the first word of "otool64", so it can be a program name with args.
  5685   5693   set dummy otool64; ac_word=$2
  5686   5694   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  5687   5695   $as_echo_n "checking for $ac_word... " >&6; }
  5688         -if test "${ac_cv_prog_ac_ct_OTOOL64+set}" = set; then :
         5696  +if ${ac_cv_prog_ac_ct_OTOOL64+:} false; then :
  5689   5697     $as_echo_n "(cached) " >&6
  5690   5698   else
  5691   5699     if test -n "$ac_ct_OTOOL64"; then
  5692   5700     ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test.
  5693   5701   else
  5694   5702   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  5695   5703   for as_dir in $PATH
................................................................................
  5756   5764   
  5757   5765   
  5758   5766   
  5759   5767   
  5760   5768   
  5761   5769       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -single_module linker flag" >&5
  5762   5770   $as_echo_n "checking for -single_module linker flag... " >&6; }
  5763         -if test "${lt_cv_apple_cc_single_mod+set}" = set; then :
         5771  +if ${lt_cv_apple_cc_single_mod+:} false; then :
  5764   5772     $as_echo_n "(cached) " >&6
  5765   5773   else
  5766   5774     lt_cv_apple_cc_single_mod=no
  5767   5775         if test -z "${LT_MULTI_MODULE}"; then
  5768   5776   	# By default we will add the -single_module flag. You can override
  5769   5777   	# by either setting the environment variable LT_MULTI_MODULE
  5770   5778   	# non-empty at configure time, or by adding -multi_module to the
................................................................................
  5785   5793   	rm -f conftest.*
  5786   5794         fi
  5787   5795   fi
  5788   5796   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5
  5789   5797   $as_echo "$lt_cv_apple_cc_single_mod" >&6; }
  5790   5798       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5
  5791   5799   $as_echo_n "checking for -exported_symbols_list linker flag... " >&6; }
  5792         -if test "${lt_cv_ld_exported_symbols_list+set}" = set; then :
         5800  +if ${lt_cv_ld_exported_symbols_list+:} false; then :
  5793   5801     $as_echo_n "(cached) " >&6
  5794   5802   else
  5795   5803     lt_cv_ld_exported_symbols_list=no
  5796   5804         save_LDFLAGS=$LDFLAGS
  5797   5805         echo "_main" > conftest.sym
  5798   5806         LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym"
  5799   5807         cat confdefs.h - <<_ACEOF >conftest.$ac_ext
................................................................................
  5862   5870   { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5
  5863   5871   $as_echo_n "checking how to run the C preprocessor... " >&6; }
  5864   5872   # On Suns, sometimes $CPP names a directory.
  5865   5873   if test -n "$CPP" && test -d "$CPP"; then
  5866   5874     CPP=
  5867   5875   fi
  5868   5876   if test -z "$CPP"; then
  5869         -  if test "${ac_cv_prog_CPP+set}" = set; then :
         5877  +  if ${ac_cv_prog_CPP+:} false; then :
  5870   5878     $as_echo_n "(cached) " >&6
  5871   5879   else
  5872   5880         # Double quotes because CPP needs to be expanded
  5873   5881       for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp"
  5874   5882       do
  5875   5883         ac_preproc_ok=false
  5876   5884   for ac_c_preproc_warn_flag in '' yes
................................................................................
  5978   5986   rm -f conftest.i conftest.err conftest.$ac_ext
  5979   5987   if $ac_preproc_ok; then :
  5980   5988   
  5981   5989   else
  5982   5990     { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
  5983   5991   $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
  5984   5992   as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
  5985         -See \`config.log' for more details" "$LINENO" 5 ; }
         5993  +See \`config.log' for more details" "$LINENO" 5; }
  5986   5994   fi
  5987   5995   
  5988   5996   ac_ext=c
  5989   5997   ac_cpp='$CPP $CPPFLAGS'
  5990   5998   ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
  5991   5999   ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
  5992   6000   ac_compiler_gnu=$ac_cv_c_compiler_gnu
  5993   6001   
  5994   6002   
  5995   6003   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
  5996   6004   $as_echo_n "checking for ANSI C header files... " >&6; }
  5997         -if test "${ac_cv_header_stdc+set}" = set; then :
         6005  +if ${ac_cv_header_stdc+:} false; then :
  5998   6006     $as_echo_n "(cached) " >&6
  5999   6007   else
  6000   6008     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  6001   6009   /* end confdefs.h.  */
  6002   6010   #include <stdlib.h>
  6003   6011   #include <stdarg.h>
  6004   6012   #include <string.h>
................................................................................
  6121   6129   done
  6122   6130   
  6123   6131   
  6124   6132   for ac_header in dlfcn.h
  6125   6133   do :
  6126   6134     ac_fn_c_check_header_compile "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default
  6127   6135   "
  6128         -if test "x$ac_cv_header_dlfcn_h" = x""yes; then :
         6136  +if test "x$ac_cv_header_dlfcn_h" = xyes; then :
  6129   6137     cat >>confdefs.h <<_ACEOF
  6130   6138   #define HAVE_DLFCN_H 1
  6131   6139   _ACEOF
  6132   6140   
  6133   6141   fi
  6134   6142   
  6135   6143   done
................................................................................
  6305   6313   
  6306   6314   if test -n "${ZSH_VERSION+set}" ; then
  6307   6315      setopt NO_GLOB_SUBST
  6308   6316   fi
  6309   6317   
  6310   6318   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for objdir" >&5
  6311   6319   $as_echo_n "checking for objdir... " >&6; }
  6312         -if test "${lt_cv_objdir+set}" = set; then :
         6320  +if ${lt_cv_objdir+:} false; then :
  6313   6321     $as_echo_n "(cached) " >&6
  6314   6322   else
  6315   6323     rm -f .libs 2>/dev/null
  6316   6324   mkdir .libs 2>/dev/null
  6317   6325   if test -d .libs; then
  6318   6326     lt_cv_objdir=.libs
  6319   6327   else
................................................................................
  6413   6421   # Only perform the check for file, if the check method requires it
  6414   6422   test -z "$MAGIC_CMD" && MAGIC_CMD=file
  6415   6423   case $deplibs_check_method in
  6416   6424   file_magic*)
  6417   6425     if test "$file_magic_cmd" = '$MAGIC_CMD'; then
  6418   6426       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${ac_tool_prefix}file" >&5
  6419   6427   $as_echo_n "checking for ${ac_tool_prefix}file... " >&6; }
  6420         -if test "${lt_cv_path_MAGIC_CMD+set}" = set; then :
         6428  +if ${lt_cv_path_MAGIC_CMD+:} false; then :
  6421   6429     $as_echo_n "(cached) " >&6
  6422   6430   else
  6423   6431     case $MAGIC_CMD in
  6424   6432   [\\/*] |  ?:[\\/]*)
  6425   6433     lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
  6426   6434     ;;
  6427   6435   *)
................................................................................
  6479   6487   
  6480   6488   
  6481   6489   
  6482   6490   if test -z "$lt_cv_path_MAGIC_CMD"; then
  6483   6491     if test -n "$ac_tool_prefix"; then
  6484   6492       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for file" >&5
  6485   6493   $as_echo_n "checking for file... " >&6; }
  6486         -if test "${lt_cv_path_MAGIC_CMD+set}" = set; then :
         6494  +if ${lt_cv_path_MAGIC_CMD+:} false; then :
  6487   6495     $as_echo_n "(cached) " >&6
  6488   6496   else
  6489   6497     case $MAGIC_CMD in
  6490   6498   [\\/*] |  ?:[\\/]*)
  6491   6499     lt_cv_path_MAGIC_CMD="$MAGIC_CMD" # Let the user override the test with a path.
  6492   6500     ;;
  6493   6501   *)
................................................................................
  6612   6620   lt_prog_compiler_no_builtin_flag=
  6613   6621   
  6614   6622   if test "$GCC" = yes; then
  6615   6623     lt_prog_compiler_no_builtin_flag=' -fno-builtin'
  6616   6624   
  6617   6625     { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -fno-rtti -fno-exceptions" >&5
  6618   6626   $as_echo_n "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; }
  6619         -if test "${lt_cv_prog_compiler_rtti_exceptions+set}" = set; then :
         6627  +if ${lt_cv_prog_compiler_rtti_exceptions+:} false; then :
  6620   6628     $as_echo_n "(cached) " >&6
  6621   6629   else
  6622   6630     lt_cv_prog_compiler_rtti_exceptions=no
  6623   6631      ac_outfile=conftest.$ac_objext
  6624   6632      echo "$lt_simple_compile_test_code" > conftest.$ac_ext
  6625   6633      lt_compiler_flag="-fno-rtti -fno-exceptions"
  6626   6634      # Insert the option either (1) after the last *FLAGS variable, or
................................................................................
  6628   6636      # Note that $ac_compile itself does not contain backslashes and begins
  6629   6637      # with a dollar sign (not a hyphen), so the echo should work correctly.
  6630   6638      # The option is referenced via a variable to avoid confusing sed.
  6631   6639      lt_compile=`echo "$ac_compile" | $SED \
  6632   6640      -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
  6633   6641      -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
  6634   6642      -e 's:$: $lt_compiler_flag:'`
  6635         -   (eval echo "\"\$as_me:6635: $lt_compile\"" >&5)
         6643  +   (eval echo "\"\$as_me:6643: $lt_compile\"" >&5)
  6636   6644      (eval "$lt_compile" 2>conftest.err)
  6637   6645      ac_status=$?
  6638   6646      cat conftest.err >&5
  6639         -   echo "$as_me:6639: \$? = $ac_status" >&5
         6647  +   echo "$as_me:6647: \$? = $ac_status" >&5
  6640   6648      if (exit $ac_status) && test -s "$ac_outfile"; then
  6641   6649        # The compiler can only warn and ignore the option if not recognized
  6642   6650        # So say no if there are warnings other than the usual output.
  6643   6651        $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
  6644   6652        $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
  6645   6653        if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
  6646   6654          lt_cv_prog_compiler_rtti_exceptions=yes
................................................................................
  6951   6959   
  6952   6960   #
  6953   6961   # Check to make sure the PIC flag actually works.
  6954   6962   #
  6955   6963   if test -n "$lt_prog_compiler_pic"; then
  6956   6964     { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5
  6957   6965   $as_echo_n "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; }
  6958         -if test "${lt_cv_prog_compiler_pic_works+set}" = set; then :
         6966  +if ${lt_cv_prog_compiler_pic_works+:} false; then :
  6959   6967     $as_echo_n "(cached) " >&6
  6960   6968   else
  6961   6969     lt_cv_prog_compiler_pic_works=no
  6962   6970      ac_outfile=conftest.$ac_objext
  6963   6971      echo "$lt_simple_compile_test_code" > conftest.$ac_ext
  6964   6972      lt_compiler_flag="$lt_prog_compiler_pic -DPIC"
  6965   6973      # Insert the option either (1) after the last *FLAGS variable, or
................................................................................
  6967   6975      # Note that $ac_compile itself does not contain backslashes and begins
  6968   6976      # with a dollar sign (not a hyphen), so the echo should work correctly.
  6969   6977      # The option is referenced via a variable to avoid confusing sed.
  6970   6978      lt_compile=`echo "$ac_compile" | $SED \
  6971   6979      -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
  6972   6980      -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
  6973   6981      -e 's:$: $lt_compiler_flag:'`
  6974         -   (eval echo "\"\$as_me:6974: $lt_compile\"" >&5)
         6982  +   (eval echo "\"\$as_me:6982: $lt_compile\"" >&5)
  6975   6983      (eval "$lt_compile" 2>conftest.err)
  6976   6984      ac_status=$?
  6977   6985      cat conftest.err >&5
  6978         -   echo "$as_me:6978: \$? = $ac_status" >&5
         6986  +   echo "$as_me:6986: \$? = $ac_status" >&5
  6979   6987      if (exit $ac_status) && test -s "$ac_outfile"; then
  6980   6988        # The compiler can only warn and ignore the option if not recognized
  6981   6989        # So say no if there are warnings other than the usual output.
  6982   6990        $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' >conftest.exp
  6983   6991        $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2
  6984   6992        if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then
  6985   6993          lt_cv_prog_compiler_pic_works=yes
................................................................................
  7010   7018   
  7011   7019   #
  7012   7020   # Check to make sure the static flag actually works.
  7013   7021   #
  7014   7022   wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\"
  7015   7023   { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5
  7016   7024   $as_echo_n "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; }
  7017         -if test "${lt_cv_prog_compiler_static_works+set}" = set; then :
         7025  +if ${lt_cv_prog_compiler_static_works+:} false; then :
  7018   7026     $as_echo_n "(cached) " >&6
  7019   7027   else
  7020   7028     lt_cv_prog_compiler_static_works=no
  7021   7029      save_LDFLAGS="$LDFLAGS"
  7022   7030      LDFLAGS="$LDFLAGS $lt_tmp_static_flag"
  7023   7031      echo "$lt_simple_link_test_code" > conftest.$ac_ext
  7024   7032      if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then
................................................................................
  7053   7061   
  7054   7062   
  7055   7063   
  7056   7064   
  7057   7065   
  7058   7066     { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
  7059   7067   $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
  7060         -if test "${lt_cv_prog_compiler_c_o+set}" = set; then :
         7068  +if ${lt_cv_prog_compiler_c_o+:} false; then :
  7061   7069     $as_echo_n "(cached) " >&6
  7062   7070   else
  7063   7071     lt_cv_prog_compiler_c_o=no
  7064   7072      $RM -r conftest 2>/dev/null
  7065   7073      mkdir conftest
  7066   7074      cd conftest
  7067   7075      mkdir out
................................................................................
  7072   7080      # (2) before a word containing "conftest.", or (3) at the end.
  7073   7081      # Note that $ac_compile itself does not contain backslashes and begins
  7074   7082      # with a dollar sign (not a hyphen), so the echo should work correctly.
  7075   7083      lt_compile=`echo "$ac_compile" | $SED \
  7076   7084      -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
  7077   7085      -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
  7078   7086      -e 's:$: $lt_compiler_flag:'`
  7079         -   (eval echo "\"\$as_me:7079: $lt_compile\"" >&5)
         7087  +   (eval echo "\"\$as_me:7087: $lt_compile\"" >&5)
  7080   7088      (eval "$lt_compile" 2>out/conftest.err)
  7081   7089      ac_status=$?
  7082   7090      cat out/conftest.err >&5
  7083         -   echo "$as_me:7083: \$? = $ac_status" >&5
         7091  +   echo "$as_me:7091: \$? = $ac_status" >&5
  7084   7092      if (exit $ac_status) && test -s out/conftest2.$ac_objext
  7085   7093      then
  7086   7094        # The compiler can only warn and ignore the option if not recognized
  7087   7095        # So say no if there are warnings
  7088   7096        $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
  7089   7097        $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
  7090   7098        if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
................................................................................
  7108   7116   
  7109   7117   
  7110   7118   
  7111   7119   
  7112   7120   
  7113   7121     { $as_echo "$as_me:${as_lineno-$LINENO}: checking if $compiler supports -c -o file.$ac_objext" >&5
  7114   7122   $as_echo_n "checking if $compiler supports -c -o file.$ac_objext... " >&6; }
  7115         -if test "${lt_cv_prog_compiler_c_o+set}" = set; then :
         7123  +if ${lt_cv_prog_compiler_c_o+:} false; then :
  7116   7124     $as_echo_n "(cached) " >&6
  7117   7125   else
  7118   7126     lt_cv_prog_compiler_c_o=no
  7119   7127      $RM -r conftest 2>/dev/null
  7120   7128      mkdir conftest
  7121   7129      cd conftest
  7122   7130      mkdir out
................................................................................
  7127   7135      # (2) before a word containing "conftest.", or (3) at the end.
  7128   7136      # Note that $ac_compile itself does not contain backslashes and begins
  7129   7137      # with a dollar sign (not a hyphen), so the echo should work correctly.
  7130   7138      lt_compile=`echo "$ac_compile" | $SED \
  7131   7139      -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \
  7132   7140      -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \
  7133   7141      -e 's:$: $lt_compiler_flag:'`
  7134         -   (eval echo "\"\$as_me:7134: $lt_compile\"" >&5)
         7142  +   (eval echo "\"\$as_me:7142: $lt_compile\"" >&5)
  7135   7143      (eval "$lt_compile" 2>out/conftest.err)
  7136   7144      ac_status=$?
  7137   7145      cat out/conftest.err >&5
  7138         -   echo "$as_me:7138: \$? = $ac_status" >&5
         7146  +   echo "$as_me:7146: \$? = $ac_status" >&5
  7139   7147      if (exit $ac_status) && test -s out/conftest2.$ac_objext
  7140   7148      then
  7141   7149        # The compiler can only warn and ignore the option if not recognized
  7142   7150        # So say no if there are warnings
  7143   7151        $ECHO "X$_lt_compiler_boilerplate" | $Xsed -e '/^$/d' > out/conftest.exp
  7144   7152        $SED '/^$/d; /^ *+/d' out/conftest.err >out/conftest.er2
  7145   7153        if test ! -s out/conftest.er2 || diff out/conftest.exp out/conftest.er2 >/dev/null; then
................................................................................
  9249   9257       lt_cv_dlopen_libs=
  9250   9258       ;;
  9251   9259   
  9252   9260     darwin*)
  9253   9261     # if libdl is installed we need to link against it
  9254   9262       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
  9255   9263   $as_echo_n "checking for dlopen in -ldl... " >&6; }
  9256         -if test "${ac_cv_lib_dl_dlopen+set}" = set; then :
         9264  +if ${ac_cv_lib_dl_dlopen+:} false; then :
  9257   9265     $as_echo_n "(cached) " >&6
  9258   9266   else
  9259   9267     ac_check_lib_save_LIBS=$LIBS
  9260   9268   LIBS="-ldl  $LIBS"
  9261   9269   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  9262   9270   /* end confdefs.h.  */
  9263   9271   
................................................................................
  9283   9291   fi
  9284   9292   rm -f core conftest.err conftest.$ac_objext \
  9285   9293       conftest$ac_exeext conftest.$ac_ext
  9286   9294   LIBS=$ac_check_lib_save_LIBS
  9287   9295   fi
  9288   9296   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
  9289   9297   $as_echo "$ac_cv_lib_dl_dlopen" >&6; }
  9290         -if test "x$ac_cv_lib_dl_dlopen" = x""yes; then :
         9298  +if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
  9291   9299     lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
  9292   9300   else
  9293   9301   
  9294   9302       lt_cv_dlopen="dyld"
  9295   9303       lt_cv_dlopen_libs=
  9296   9304       lt_cv_dlopen_self=yes
  9297   9305   
  9298   9306   fi
  9299   9307   
  9300   9308       ;;
  9301   9309   
  9302   9310     *)
  9303   9311       ac_fn_c_check_func "$LINENO" "shl_load" "ac_cv_func_shl_load"
  9304         -if test "x$ac_cv_func_shl_load" = x""yes; then :
         9312  +if test "x$ac_cv_func_shl_load" = xyes; then :
  9305   9313     lt_cv_dlopen="shl_load"
  9306   9314   else
  9307   9315     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5
  9308   9316   $as_echo_n "checking for shl_load in -ldld... " >&6; }
  9309         -if test "${ac_cv_lib_dld_shl_load+set}" = set; then :
         9317  +if ${ac_cv_lib_dld_shl_load+:} false; then :
  9310   9318     $as_echo_n "(cached) " >&6
  9311   9319   else
  9312   9320     ac_check_lib_save_LIBS=$LIBS
  9313   9321   LIBS="-ldld  $LIBS"
  9314   9322   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  9315   9323   /* end confdefs.h.  */
  9316   9324   
................................................................................
  9336   9344   fi
  9337   9345   rm -f core conftest.err conftest.$ac_objext \
  9338   9346       conftest$ac_exeext conftest.$ac_ext
  9339   9347   LIBS=$ac_check_lib_save_LIBS
  9340   9348   fi
  9341   9349   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5
  9342   9350   $as_echo "$ac_cv_lib_dld_shl_load" >&6; }
  9343         -if test "x$ac_cv_lib_dld_shl_load" = x""yes; then :
         9351  +if test "x$ac_cv_lib_dld_shl_load" = xyes; then :
  9344   9352     lt_cv_dlopen="shl_load" lt_cv_dlopen_libs="-ldld"
  9345   9353   else
  9346   9354     ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen"
  9347         -if test "x$ac_cv_func_dlopen" = x""yes; then :
         9355  +if test "x$ac_cv_func_dlopen" = xyes; then :
  9348   9356     lt_cv_dlopen="dlopen"
  9349   9357   else
  9350   9358     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
  9351   9359   $as_echo_n "checking for dlopen in -ldl... " >&6; }
  9352         -if test "${ac_cv_lib_dl_dlopen+set}" = set; then :
         9360  +if ${ac_cv_lib_dl_dlopen+:} false; then :
  9353   9361     $as_echo_n "(cached) " >&6
  9354   9362   else
  9355   9363     ac_check_lib_save_LIBS=$LIBS
  9356   9364   LIBS="-ldl  $LIBS"
  9357   9365   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  9358   9366   /* end confdefs.h.  */
  9359   9367   
................................................................................
  9379   9387   fi
  9380   9388   rm -f core conftest.err conftest.$ac_objext \
  9381   9389       conftest$ac_exeext conftest.$ac_ext
  9382   9390   LIBS=$ac_check_lib_save_LIBS
  9383   9391   fi
  9384   9392   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5
  9385   9393   $as_echo "$ac_cv_lib_dl_dlopen" >&6; }
  9386         -if test "x$ac_cv_lib_dl_dlopen" = x""yes; then :
         9394  +if test "x$ac_cv_lib_dl_dlopen" = xyes; then :
  9387   9395     lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-ldl"
  9388   9396   else
  9389   9397     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5
  9390   9398   $as_echo_n "checking for dlopen in -lsvld... " >&6; }
  9391         -if test "${ac_cv_lib_svld_dlopen+set}" = set; then :
         9399  +if ${ac_cv_lib_svld_dlopen+:} false; then :
  9392   9400     $as_echo_n "(cached) " >&6
  9393   9401   else
  9394   9402     ac_check_lib_save_LIBS=$LIBS
  9395   9403   LIBS="-lsvld  $LIBS"
  9396   9404   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  9397   9405   /* end confdefs.h.  */
  9398   9406   
................................................................................
  9418   9426   fi
  9419   9427   rm -f core conftest.err conftest.$ac_objext \
  9420   9428       conftest$ac_exeext conftest.$ac_ext
  9421   9429   LIBS=$ac_check_lib_save_LIBS
  9422   9430   fi
  9423   9431   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5
  9424   9432   $as_echo "$ac_cv_lib_svld_dlopen" >&6; }
  9425         -if test "x$ac_cv_lib_svld_dlopen" = x""yes; then :
         9433  +if test "x$ac_cv_lib_svld_dlopen" = xyes; then :
  9426   9434     lt_cv_dlopen="dlopen" lt_cv_dlopen_libs="-lsvld"
  9427   9435   else
  9428   9436     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5
  9429   9437   $as_echo_n "checking for dld_link in -ldld... " >&6; }
  9430         -if test "${ac_cv_lib_dld_dld_link+set}" = set; then :
         9438  +if ${ac_cv_lib_dld_dld_link+:} false; then :
  9431   9439     $as_echo_n "(cached) " >&6
  9432   9440   else
  9433   9441     ac_check_lib_save_LIBS=$LIBS
  9434   9442   LIBS="-ldld  $LIBS"
  9435   9443   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
  9436   9444   /* end confdefs.h.  */
  9437   9445   
................................................................................
  9457   9465   fi
  9458   9466   rm -f core conftest.err conftest.$ac_objext \
  9459   9467       conftest$ac_exeext conftest.$ac_ext
  9460   9468   LIBS=$ac_check_lib_save_LIBS
  9461   9469   fi
  9462   9470   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5
  9463   9471   $as_echo "$ac_cv_lib_dld_dld_link" >&6; }
  9464         -if test "x$ac_cv_lib_dld_dld_link" = x""yes; then :
         9472  +if test "x$ac_cv_lib_dld_dld_link" = xyes; then :
  9465   9473     lt_cv_dlopen="dld_link" lt_cv_dlopen_libs="-ldld"
  9466   9474   fi
  9467   9475   
  9468   9476   
  9469   9477   fi
  9470   9478   
  9471   9479   
................................................................................
  9498   9506       wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $export_dynamic_flag_spec\"
  9499   9507   
  9500   9508       save_LIBS="$LIBS"
  9501   9509       LIBS="$lt_cv_dlopen_libs $LIBS"
  9502   9510   
  9503   9511       { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a program can dlopen itself" >&5
  9504   9512   $as_echo_n "checking whether a program can dlopen itself... " >&6; }
  9505         -if test "${lt_cv_dlopen_self+set}" = set; then :
         9513  +if ${lt_cv_dlopen_self+:} false; then :
  9506   9514     $as_echo_n "(cached) " >&6
  9507   9515   else
  9508   9516     	  if test "$cross_compiling" = yes; then :
  9509   9517     lt_cv_dlopen_self=cross
  9510   9518   else
  9511   9519     lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
  9512   9520     lt_status=$lt_dlunknown
  9513   9521     cat > conftest.$ac_ext <<_LT_EOF
  9514         -#line 9514 "configure"
         9522  +#line 9522 "configure"
  9515   9523   #include "confdefs.h"
  9516   9524   
  9517   9525   #if HAVE_DLFCN_H
  9518   9526   #include <dlfcn.h>
  9519   9527   #endif
  9520   9528   
  9521   9529   #include <stdio.h>
................................................................................
  9594   9602   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5
  9595   9603   $as_echo "$lt_cv_dlopen_self" >&6; }
  9596   9604   
  9597   9605       if test "x$lt_cv_dlopen_self" = xyes; then
  9598   9606         wl=$lt_prog_compiler_wl eval LDFLAGS=\"\$LDFLAGS $lt_prog_compiler_static\"
  9599   9607         { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether a statically linked program can dlopen itself" >&5
  9600   9608   $as_echo_n "checking whether a statically linked program can dlopen itself... " >&6; }
  9601         -if test "${lt_cv_dlopen_self_static+set}" = set; then :
         9609  +if ${lt_cv_dlopen_self_static+:} false; then :
  9602   9610     $as_echo_n "(cached) " >&6
  9603   9611   else
  9604   9612     	  if test "$cross_compiling" = yes; then :
  9605   9613     lt_cv_dlopen_self_static=cross
  9606   9614   else
  9607   9615     lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2
  9608   9616     lt_status=$lt_dlunknown
  9609   9617     cat > conftest.$ac_ext <<_LT_EOF
  9610         -#line 9610 "configure"
         9618  +#line 9618 "configure"
  9611   9619   #include "confdefs.h"
  9612   9620   
  9613   9621   #if HAVE_DLFCN_H
  9614   9622   #include <dlfcn.h>
  9615   9623   #endif
  9616   9624   
  9617   9625   #include <stdio.h>
................................................................................
  9847   9855   # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
  9848   9856   # OS/2's system install, which has a completely different semantic
  9849   9857   # ./install, which can be erroneously created by make from ./install.sh.
  9850   9858   # Reject install programs that cannot install multiple files.
  9851   9859   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5
  9852   9860   $as_echo_n "checking for a BSD-compatible install... " >&6; }
  9853   9861   if test -z "$INSTALL"; then
  9854         -if test "${ac_cv_path_install+set}" = set; then :
         9862  +if ${ac_cv_path_install+:} false; then :
  9855   9863     $as_echo_n "(cached) " >&6
  9856   9864   else
  9857   9865     as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  9858   9866   for as_dir in $PATH
  9859   9867   do
  9860   9868     IFS=$as_save_IFS
  9861   9869     test -z "$as_dir" && as_dir=.
................................................................................
  9929   9937   
  9930   9938   for ac_prog in gawk mawk nawk awk
  9931   9939   do
  9932   9940     # Extract the first word of "$ac_prog", so it can be a program name with args.
  9933   9941   set dummy $ac_prog; ac_word=$2
  9934   9942   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
  9935   9943   $as_echo_n "checking for $ac_word... " >&6; }
  9936         -if test "${ac_cv_prog_AWK+set}" = set; then :
         9944  +if ${ac_cv_prog_AWK+:} false; then :
  9937   9945     $as_echo_n "(cached) " >&6
  9938   9946   else
  9939   9947     if test -n "$AWK"; then
  9940   9948     ac_cv_prog_AWK="$AWK" # Let the user override the test.
  9941   9949   else
  9942   9950   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
  9943   9951   for as_dir in $PATH
................................................................................
  9978   9986     enableval=$enable_largefile;
  9979   9987   fi
  9980   9988   
  9981   9989   if test "$enable_largefile" != no; then
  9982   9990   
  9983   9991     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5
  9984   9992   $as_echo_n "checking for special C compiler options needed for large files... " >&6; }
  9985         -if test "${ac_cv_sys_largefile_CC+set}" = set; then :
         9993  +if ${ac_cv_sys_largefile_CC+:} false; then :
  9986   9994     $as_echo_n "(cached) " >&6
  9987   9995   else
  9988   9996     ac_cv_sys_largefile_CC=no
  9989   9997        if test "$GCC" != yes; then
  9990   9998          ac_save_CC=$CC
  9991   9999          while :; do
  9992  10000   	 # IRIX 6.2 and later do not support large files by default,
................................................................................
 10029  10037   $as_echo "$ac_cv_sys_largefile_CC" >&6; }
 10030  10038     if test "$ac_cv_sys_largefile_CC" != no; then
 10031  10039       CC=$CC$ac_cv_sys_largefile_CC
 10032  10040     fi
 10033  10041   
 10034  10042     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5
 10035  10043   $as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; }
 10036         -if test "${ac_cv_sys_file_offset_bits+set}" = set; then :
        10044  +if ${ac_cv_sys_file_offset_bits+:} false; then :
 10037  10045     $as_echo_n "(cached) " >&6
 10038  10046   else
 10039  10047     while :; do
 10040  10048     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 10041  10049   /* end confdefs.h.  */
 10042  10050   #include <sys/types.h>
 10043  10051    /* Check that off_t can represent 2**63 - 1 correctly.
................................................................................
 10098  10106   _ACEOF
 10099  10107   ;;
 10100  10108   esac
 10101  10109   rm -rf conftest*
 10102  10110     if test $ac_cv_sys_file_offset_bits = unknown; then
 10103  10111       { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5
 10104  10112   $as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; }
 10105         -if test "${ac_cv_sys_large_files+set}" = set; then :
        10113  +if ${ac_cv_sys_large_files+:} false; then :
 10106  10114     $as_echo_n "(cached) " >&6
 10107  10115   else
 10108  10116     while :; do
 10109  10117     cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 10110  10118   /* end confdefs.h.  */
 10111  10119   #include <sys/types.h>
 10112  10120    /* Check that off_t can represent 2**63 - 1 correctly.
................................................................................
 10171  10179     fi
 10172  10180   fi
 10173  10181   
 10174  10182   
 10175  10183   #########
 10176  10184   # Check for needed/wanted data types
 10177  10185   ac_fn_c_check_type "$LINENO" "int8_t" "ac_cv_type_int8_t" "$ac_includes_default"
 10178         -if test "x$ac_cv_type_int8_t" = x""yes; then :
        10186  +if test "x$ac_cv_type_int8_t" = xyes; then :
 10179  10187   
 10180  10188   cat >>confdefs.h <<_ACEOF
 10181  10189   #define HAVE_INT8_T 1
 10182  10190   _ACEOF
 10183  10191   
 10184  10192   
 10185  10193   fi
 10186  10194   ac_fn_c_check_type "$LINENO" "int16_t" "ac_cv_type_int16_t" "$ac_includes_default"
 10187         -if test "x$ac_cv_type_int16_t" = x""yes; then :
        10195  +if test "x$ac_cv_type_int16_t" = xyes; then :
 10188  10196   
 10189  10197   cat >>confdefs.h <<_ACEOF
 10190  10198   #define HAVE_INT16_T 1
 10191  10199   _ACEOF
 10192  10200   
 10193  10201   
 10194  10202   fi
 10195  10203   ac_fn_c_check_type "$LINENO" "int32_t" "ac_cv_type_int32_t" "$ac_includes_default"
 10196         -if test "x$ac_cv_type_int32_t" = x""yes; then :
        10204  +if test "x$ac_cv_type_int32_t" = xyes; then :
 10197  10205   
 10198  10206   cat >>confdefs.h <<_ACEOF
 10199  10207   #define HAVE_INT32_T 1
 10200  10208   _ACEOF
 10201  10209   
 10202  10210   
 10203  10211   fi
 10204  10212   ac_fn_c_check_type "$LINENO" "int64_t" "ac_cv_type_int64_t" "$ac_includes_default"
 10205         -if test "x$ac_cv_type_int64_t" = x""yes; then :
        10213  +if test "x$ac_cv_type_int64_t" = xyes; then :
 10206  10214   
 10207  10215   cat >>confdefs.h <<_ACEOF
 10208  10216   #define HAVE_INT64_T 1
 10209  10217   _ACEOF
 10210  10218   
 10211  10219   
 10212  10220   fi
 10213  10221   ac_fn_c_check_type "$LINENO" "intptr_t" "ac_cv_type_intptr_t" "$ac_includes_default"
 10214         -if test "x$ac_cv_type_intptr_t" = x""yes; then :
        10222  +if test "x$ac_cv_type_intptr_t" = xyes; then :
 10215  10223   
 10216  10224   cat >>confdefs.h <<_ACEOF
 10217  10225   #define HAVE_INTPTR_T 1
 10218  10226   _ACEOF
 10219  10227   
 10220  10228   
 10221  10229   fi
 10222  10230   ac_fn_c_check_type "$LINENO" "uint8_t" "ac_cv_type_uint8_t" "$ac_includes_default"
 10223         -if test "x$ac_cv_type_uint8_t" = x""yes; then :
        10231  +if test "x$ac_cv_type_uint8_t" = xyes; then :
 10224  10232   
 10225  10233   cat >>confdefs.h <<_ACEOF
 10226  10234   #define HAVE_UINT8_T 1
 10227  10235   _ACEOF
 10228  10236   
 10229  10237   
 10230  10238   fi
 10231  10239   ac_fn_c_check_type "$LINENO" "uint16_t" "ac_cv_type_uint16_t" "$ac_includes_default"
 10232         -if test "x$ac_cv_type_uint16_t" = x""yes; then :
        10240  +if test "x$ac_cv_type_uint16_t" = xyes; then :
 10233  10241   
 10234  10242   cat >>confdefs.h <<_ACEOF
 10235  10243   #define HAVE_UINT16_T 1
 10236  10244   _ACEOF
 10237  10245   
 10238  10246   
 10239  10247   fi
 10240  10248   ac_fn_c_check_type "$LINENO" "uint32_t" "ac_cv_type_uint32_t" "$ac_includes_default"
 10241         -if test "x$ac_cv_type_uint32_t" = x""yes; then :
        10249  +if test "x$ac_cv_type_uint32_t" = xyes; then :
 10242  10250   
 10243  10251   cat >>confdefs.h <<_ACEOF
 10244  10252   #define HAVE_UINT32_T 1
 10245  10253   _ACEOF
 10246  10254   
 10247  10255   
 10248  10256   fi
 10249  10257   ac_fn_c_check_type "$LINENO" "uint64_t" "ac_cv_type_uint64_t" "$ac_includes_default"
 10250         -if test "x$ac_cv_type_uint64_t" = x""yes; then :
        10258  +if test "x$ac_cv_type_uint64_t" = xyes; then :
 10251  10259   
 10252  10260   cat >>confdefs.h <<_ACEOF
 10253  10261   #define HAVE_UINT64_T 1
 10254  10262   _ACEOF
 10255  10263   
 10256  10264   
 10257  10265   fi
 10258  10266   ac_fn_c_check_type "$LINENO" "uintptr_t" "ac_cv_type_uintptr_t" "$ac_includes_default"
 10259         -if test "x$ac_cv_type_uintptr_t" = x""yes; then :
        10267  +if test "x$ac_cv_type_uintptr_t" = xyes; then :
 10260  10268   
 10261  10269   cat >>confdefs.h <<_ACEOF
 10262  10270   #define HAVE_UINTPTR_T 1
 10263  10271   _ACEOF
 10264  10272   
 10265  10273   
 10266  10274   fi
................................................................................
 10281  10289   
 10282  10290   done
 10283  10291   
 10284  10292   
 10285  10293   #########
 10286  10294   # Figure out whether or not we have these functions
 10287  10295   #
 10288         -for ac_func in usleep fdatasync localtime_r gmtime_r localtime_s utime
        10296  +for ac_func in usleep fdatasync localtime_r gmtime_r localtime_s utime malloc_usable_size
 10289  10297   do :
 10290  10298     as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
 10291  10299   ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
 10292  10300   if eval test \"x\$"$as_ac_var"\" = x"yes"; then :
 10293  10301     cat >>confdefs.h <<_ACEOF
 10294  10302   #define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1
 10295  10303   _ACEOF
................................................................................
 10310  10318   #
 10311  10319   for ac_prog in tclsh8.5 tclsh
 10312  10320   do
 10313  10321     # Extract the first word of "$ac_prog", so it can be a program name with args.
 10314  10322   set dummy $ac_prog; ac_word=$2
 10315  10323   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 10316  10324   $as_echo_n "checking for $ac_word... " >&6; }
 10317         -if test "${ac_cv_prog_TCLSH_CMD+set}" = set; then :
        10325  +if ${ac_cv_prog_TCLSH_CMD+:} false; then :
 10318  10326     $as_echo_n "(cached) " >&6
 10319  10327   else
 10320  10328     if test -n "$TCLSH_CMD"; then
 10321  10329     ac_cv_prog_TCLSH_CMD="$TCLSH_CMD" # Let the user override the test.
 10322  10330   else
 10323  10331   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 10324  10332   for as_dir in $PATH
................................................................................
 10444  10452   	if test "${BUILD_CC+set}" != set; then
 10445  10453   		for ac_prog in gcc cc cl
 10446  10454   do
 10447  10455     # Extract the first word of "$ac_prog", so it can be a program name with args.
 10448  10456   set dummy $ac_prog; ac_word=$2
 10449  10457   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 10450  10458   $as_echo_n "checking for $ac_word... " >&6; }
 10451         -if test "${ac_cv_prog_BUILD_CC+set}" = set; then :
        10459  +if ${ac_cv_prog_BUILD_CC+:} false; then :
 10452  10460     $as_echo_n "(cached) " >&6
 10453  10461   else
 10454  10462     if test -n "$BUILD_CC"; then
 10455  10463     ac_cv_prog_BUILD_CC="$BUILD_CC" # Let the user override the test.
 10456  10464   else
 10457  10465   as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 10458  10466   for as_dir in $PATH
................................................................................
 10513  10521   $as_echo "yes" >&6; }
 10514  10522   fi
 10515  10523   
 10516  10524   
 10517  10525   if test "$SQLITE_THREADSAFE" = "1"; then
 10518  10526     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing pthread_create" >&5
 10519  10527   $as_echo_n "checking for library containing pthread_create... " >&6; }
 10520         -if test "${ac_cv_search_pthread_create+set}" = set; then :
        10528  +if ${ac_cv_search_pthread_create+:} false; then :
 10521  10529     $as_echo_n "(cached) " >&6
 10522  10530   else
 10523  10531     ac_func_search_save_LIBS=$LIBS
 10524  10532   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 10525  10533   /* end confdefs.h.  */
 10526  10534   
 10527  10535   /* Override any GCC internal prototype to avoid an error.
................................................................................
 10547  10555       LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
 10548  10556     fi
 10549  10557     if ac_fn_c_try_link "$LINENO"; then :
 10550  10558     ac_cv_search_pthread_create=$ac_res
 10551  10559   fi
 10552  10560   rm -f core conftest.err conftest.$ac_objext \
 10553  10561       conftest$ac_exeext
 10554         -  if test "${ac_cv_search_pthread_create+set}" = set; then :
        10562  +  if ${ac_cv_search_pthread_create+:} false; then :
 10555  10563     break
 10556  10564   fi
 10557  10565   done
 10558         -if test "${ac_cv_search_pthread_create+set}" = set; then :
        10566  +if ${ac_cv_search_pthread_create+:} false; then :
 10559  10567   
 10560  10568   else
 10561  10569     ac_cv_search_pthread_create=no
 10562  10570   fi
 10563  10571   rm conftest.$ac_ext
 10564  10572   LIBS=$ac_func_search_save_LIBS
 10565  10573   fi
................................................................................
 10741  10749   # Check whether --with-tcl was given.
 10742  10750   if test "${with_tcl+set}" = set; then :
 10743  10751     withval=$with_tcl; with_tclconfig=${withval}
 10744  10752   fi
 10745  10753   
 10746  10754     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Tcl configuration" >&5
 10747  10755   $as_echo_n "checking for Tcl configuration... " >&6; }
 10748         -  if test "${ac_cv_c_tclconfig+set}" = set; then :
        10756  +  if ${ac_cv_c_tclconfig+:} false; then :
 10749  10757     $as_echo_n "(cached) " >&6
 10750  10758   else
 10751  10759   
 10752  10760       # First check to see if --with-tcl was specified.
 10753  10761       if test x"${with_tclconfig}" != x ; then
 10754  10762         if test -f "${with_tclconfig}/tclConfig.sh" ; then
 10755  10763           ac_cv_c_tclconfig=`(cd ${with_tclconfig}; pwd)`
................................................................................
 10925  10933   fi
 10926  10934   
 10927  10935   	if test "x$with_readline_lib" = xauto; then
 10928  10936   		save_LIBS="$LIBS"
 10929  10937   		LIBS=""
 10930  10938   		{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing tgetent" >&5
 10931  10939   $as_echo_n "checking for library containing tgetent... " >&6; }
 10932         -if test "${ac_cv_search_tgetent+set}" = set; then :
        10940  +if ${ac_cv_search_tgetent+:} false; then :
 10933  10941     $as_echo_n "(cached) " >&6
 10934  10942   else
 10935  10943     ac_func_search_save_LIBS=$LIBS
 10936  10944   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 10937  10945   /* end confdefs.h.  */
 10938  10946   
 10939  10947   /* Override any GCC internal prototype to avoid an error.
................................................................................
 10959  10967       LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
 10960  10968     fi
 10961  10969     if ac_fn_c_try_link "$LINENO"; then :
 10962  10970     ac_cv_search_tgetent=$ac_res
 10963  10971   fi
 10964  10972   rm -f core conftest.err conftest.$ac_objext \
 10965  10973       conftest$ac_exeext
 10966         -  if test "${ac_cv_search_tgetent+set}" = set; then :
        10974  +  if ${ac_cv_search_tgetent+:} false; then :
 10967  10975     break
 10968  10976   fi
 10969  10977   done
 10970         -if test "${ac_cv_search_tgetent+set}" = set; then :
        10978  +if ${ac_cv_search_tgetent+:} false; then :
 10971  10979   
 10972  10980   else
 10973  10981     ac_cv_search_tgetent=no
 10974  10982   fi
 10975  10983   rm conftest.$ac_ext
 10976  10984   LIBS=$ac_func_search_save_LIBS
 10977  10985   fi
................................................................................
 10983  10991     term_LIBS="$LIBS"
 10984  10992   else
 10985  10993     term_LIBS=""
 10986  10994   fi
 10987  10995   
 10988  10996   		{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for readline in -lreadline" >&5
 10989  10997   $as_echo_n "checking for readline in -lreadline... " >&6; }
 10990         -if test "${ac_cv_lib_readline_readline+set}" = set; then :
        10998  +if ${ac_cv_lib_readline_readline+:} false; then :
 10991  10999     $as_echo_n "(cached) " >&6
 10992  11000   else
 10993  11001     ac_check_lib_save_LIBS=$LIBS
 10994  11002   LIBS="-lreadline  $LIBS"
 10995  11003   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 10996  11004   /* end confdefs.h.  */
 10997  11005   
................................................................................
 11017  11025   fi
 11018  11026   rm -f core conftest.err conftest.$ac_objext \
 11019  11027       conftest$ac_exeext conftest.$ac_ext
 11020  11028   LIBS=$ac_check_lib_save_LIBS
 11021  11029   fi
 11022  11030   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_readline_readline" >&5
 11023  11031   $as_echo "$ac_cv_lib_readline_readline" >&6; }
 11024         -if test "x$ac_cv_lib_readline_readline" = x""yes; then :
        11032  +if test "x$ac_cv_lib_readline_readline" = xyes; then :
 11025  11033     TARGET_READLINE_LIBS="-lreadline"
 11026  11034   else
 11027  11035     found="no"
 11028  11036   fi
 11029  11037   
 11030  11038   		TARGET_READLINE_LIBS="$TARGET_READLINE_LIBS $term_LIBS"
 11031  11039   		LIBS="$save_LIBS"
................................................................................
 11039  11047     withval=$with_readline_inc; with_readline_inc=$withval
 11040  11048   else
 11041  11049     with_readline_inc="auto"
 11042  11050   fi
 11043  11051   
 11044  11052   	if test "x$with_readline_inc" = xauto; then
 11045  11053   		ac_fn_c_check_header_mongrel "$LINENO" "readline.h" "ac_cv_header_readline_h" "$ac_includes_default"
 11046         -if test "x$ac_cv_header_readline_h" = x""yes; then :
        11054  +if test "x$ac_cv_header_readline_h" = xyes; then :
 11047  11055     found="yes"
 11048  11056   else
 11049  11057   
 11050  11058   			found="no"
 11051  11059   			if test "$cross_compiling" != yes; then
 11052  11060   				for dir in /usr /usr/local /usr/local/readline /usr/contrib /mingw; do
 11053  11061   					for subdir in include include/readline; do
 11054  11062   						as_ac_File=`$as_echo "ac_cv_file_$dir/$subdir/readline.h" | $as_tr_sh`
 11055  11063   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $dir/$subdir/readline.h" >&5
 11056  11064   $as_echo_n "checking for $dir/$subdir/readline.h... " >&6; }
 11057         -if eval "test \"\${$as_ac_File+set}\"" = set; then :
        11065  +if eval \${$as_ac_File+:} false; then :
 11058  11066     $as_echo_n "(cached) " >&6
 11059  11067   else
 11060  11068     test "$cross_compiling" = yes &&
 11061  11069     as_fn_error $? "cannot check for file existence when cross compiling" "$LINENO" 5
 11062  11070   if test -r "$dir/$subdir/readline.h"; then
 11063  11071     eval "$as_ac_File=yes"
 11064  11072   else
................................................................................
 11103  11111   
 11104  11112   ##########
 11105  11113   # Figure out what C libraries are required to compile programs
 11106  11114   # that use "fdatasync()" function.
 11107  11115   #
 11108  11116   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing fdatasync" >&5
 11109  11117   $as_echo_n "checking for library containing fdatasync... " >&6; }
 11110         -if test "${ac_cv_search_fdatasync+set}" = set; then :
        11118  +if ${ac_cv_search_fdatasync+:} false; then :
 11111  11119     $as_echo_n "(cached) " >&6
 11112  11120   else
 11113  11121     ac_func_search_save_LIBS=$LIBS
 11114  11122   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 11115  11123   /* end confdefs.h.  */
 11116  11124   
 11117  11125   /* Override any GCC internal prototype to avoid an error.
................................................................................
 11137  11145       LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
 11138  11146     fi
 11139  11147     if ac_fn_c_try_link "$LINENO"; then :
 11140  11148     ac_cv_search_fdatasync=$ac_res
 11141  11149   fi
 11142  11150   rm -f core conftest.err conftest.$ac_objext \
 11143  11151       conftest$ac_exeext
 11144         -  if test "${ac_cv_search_fdatasync+set}" = set; then :
        11152  +  if ${ac_cv_search_fdatasync+:} false; then :
 11145  11153     break
 11146  11154   fi
 11147  11155   done
 11148         -if test "${ac_cv_search_fdatasync+set}" = set; then :
        11156  +if ${ac_cv_search_fdatasync+:} false; then :
 11149  11157   
 11150  11158   else
 11151  11159     ac_cv_search_fdatasync=no
 11152  11160   fi
 11153  11161   rm conftest.$ac_ext
 11154  11162   LIBS=$ac_func_search_save_LIBS
 11155  11163   fi
................................................................................
 11201  11209     use_loadextension=no
 11202  11210   fi
 11203  11211   
 11204  11212   if test "${use_loadextension}" = "yes" ; then
 11205  11213     OPT_FEATURE_FLAGS=""
 11206  11214     { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing dlopen" >&5
 11207  11215   $as_echo_n "checking for library containing dlopen... " >&6; }
 11208         -if test "${ac_cv_search_dlopen+set}" = set; then :
        11216  +if ${ac_cv_search_dlopen+:} false; then :
 11209  11217     $as_echo_n "(cached) " >&6
 11210  11218   else
 11211  11219     ac_func_search_save_LIBS=$LIBS
 11212  11220   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 11213  11221   /* end confdefs.h.  */
 11214  11222   
 11215  11223   /* Override any GCC internal prototype to avoid an error.
................................................................................
 11235  11243       LIBS="-l$ac_lib  $ac_func_search_save_LIBS"
 11236  11244     fi
 11237  11245     if ac_fn_c_try_link "$LINENO"; then :
 11238  11246     ac_cv_search_dlopen=$ac_res
 11239  11247   fi
 11240  11248   rm -f core conftest.err conftest.$ac_objext \
 11241  11249       conftest$ac_exeext
 11242         -  if test "${ac_cv_search_dlopen+set}" = set; then :
        11250  +  if ${ac_cv_search_dlopen+:} false; then :
 11243  11251     break
 11244  11252   fi
 11245  11253   done
 11246         -if test "${ac_cv_search_dlopen+set}" = set; then :
        11254  +if ${ac_cv_search_dlopen+:} false; then :
 11247  11255   
 11248  11256   else
 11249  11257     ac_cv_search_dlopen=no
 11250  11258   fi
 11251  11259   rm conftest.$ac_ext
 11252  11260   LIBS=$ac_func_search_save_LIBS
 11253  11261   fi
................................................................................
 11402  11410        :clear
 11403  11411        s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
 11404  11412        t end
 11405  11413        s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
 11406  11414        :end' >>confcache
 11407  11415   if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
 11408  11416     if test -w "$cache_file"; then
 11409         -    test "x$cache_file" != "x/dev/null" &&
        11417  +    if test "x$cache_file" != "x/dev/null"; then
 11410  11418         { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
 11411  11419   $as_echo "$as_me: updating cache $cache_file" >&6;}
 11412         -    cat confcache >$cache_file
        11420  +      if test ! -f "$cache_file" || test -h "$cache_file"; then
        11421  +	cat confcache >"$cache_file"
        11422  +      else
        11423  +        case $cache_file in #(
        11424  +        */* | ?:*)
        11425  +	  mv -f confcache "$cache_file"$$ &&
        11426  +	  mv -f "$cache_file"$$ "$cache_file" ;; #(
        11427  +        *)
        11428  +	  mv -f confcache "$cache_file" ;;
        11429  +	esac
        11430  +      fi
        11431  +    fi
 11413  11432     else
 11414  11433       { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
 11415  11434   $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
 11416  11435     fi
 11417  11436   fi
 11418  11437   rm -f confcache
 11419  11438   
................................................................................
 11437  11456   done
 11438  11457   LIBOBJS=$ac_libobjs
 11439  11458   
 11440  11459   LTLIBOBJS=$ac_ltlibobjs
 11441  11460   
 11442  11461   
 11443  11462   
 11444         -: ${CONFIG_STATUS=./config.status}
        11463  +: "${CONFIG_STATUS=./config.status}"
 11445  11464   ac_write_fail=0
 11446  11465   ac_clean_files_save=$ac_clean_files
 11447  11466   ac_clean_files="$ac_clean_files $CONFIG_STATUS"
 11448  11467   { $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5
 11449  11468   $as_echo "$as_me: creating $CONFIG_STATUS" >&6;}
 11450  11469   as_write_fail=0
 11451  11470   cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1
................................................................................
 11538  11557   # We need space, tab and new line, in precisely that order.  Quoting is
 11539  11558   # there to prevent editors from complaining about space-tab.
 11540  11559   # (If _AS_PATH_WALK were called with IFS unset, it would disable word
 11541  11560   # splitting by setting IFS to empty value.)
 11542  11561   IFS=" ""	$as_nl"
 11543  11562   
 11544  11563   # Find who we are.  Look in the path if we contain no directory separator.
        11564  +as_myself=
 11545  11565   case $0 in #((
 11546  11566     *[\\/]* ) as_myself=$0 ;;
 11547  11567     *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 11548  11568   for as_dir in $PATH
 11549  11569   do
 11550  11570     IFS=$as_save_IFS
 11551  11571     test -z "$as_dir" && as_dir=.
................................................................................
 11844  11864   test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1
 11845  11865   
 11846  11866   cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 11847  11867   # Save the log message, to keep $0 and so on meaningful, and to
 11848  11868   # report actual input values of CONFIG_FILES etc. instead of their
 11849  11869   # values after options handling.
 11850  11870   ac_log="
 11851         -This file was extended by sqlite $as_me 3.7.9, which was
 11852         -generated by GNU Autoconf 2.67.  Invocation command line was
        11871  +This file was extended by sqlite $as_me 3.7.10, which was
        11872  +generated by GNU Autoconf 2.68.  Invocation command line was
 11853  11873   
 11854  11874     CONFIG_FILES    = $CONFIG_FILES
 11855  11875     CONFIG_HEADERS  = $CONFIG_HEADERS
 11856  11876     CONFIG_LINKS    = $CONFIG_LINKS
 11857  11877     CONFIG_COMMANDS = $CONFIG_COMMANDS
 11858  11878     $ $0 $@
 11859  11879   
................................................................................
 11910  11930   
 11911  11931   Report bugs to the package provider."
 11912  11932   
 11913  11933   _ACEOF
 11914  11934   cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 11915  11935   ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 11916  11936   ac_cs_version="\\
 11917         -sqlite config.status 3.7.9
 11918         -configured by $0, generated by GNU Autoconf 2.67,
        11937  +sqlite config.status 3.7.10
        11938  +configured by $0, generated by GNU Autoconf 2.68,
 11919  11939     with options \\"\$ac_cs_config\\"
 11920  11940   
 11921  11941   Copyright (C) 2010 Free Software Foundation, Inc.
 11922  11942   This config.status script is free software; the Free Software Foundation
 11923  11943   gives unlimited permission to copy, distribute and modify it."
 11924  11944   
 11925  11945   ac_pwd='$ac_pwd'
................................................................................
 12297  12317   do
 12298  12318     case $ac_config_target in
 12299  12319       "libtool") CONFIG_COMMANDS="$CONFIG_COMMANDS libtool" ;;
 12300  12320       "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
 12301  12321       "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
 12302  12322       "sqlite3.pc") CONFIG_FILES="$CONFIG_FILES sqlite3.pc" ;;
 12303  12323   
 12304         -  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;;
        12324  +  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
 12305  12325     esac
 12306  12326   done
 12307  12327   
 12308  12328   
 12309  12329   # If the user did not use the arguments to specify the items to instantiate,
 12310  12330   # then the envvar interface is used.  Set only those that are not.
 12311  12331   # We use the long form for the default assignment because of an extremely
................................................................................
 12320  12340   # simply because there is no reason against having it here, and in addition,
 12321  12341   # creating and moving files from /tmp can sometimes cause problems.
 12322  12342   # Hook for its removal unless debugging.
 12323  12343   # Note that there is a small window in which the directory will not be cleaned:
 12324  12344   # after its creation but before its name has been assigned to `$tmp'.
 12325  12345   $debug ||
 12326  12346   {
 12327         -  tmp=
        12347  +  tmp= ac_tmp=
 12328  12348     trap 'exit_status=$?
 12329         -  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
        12349  +  : "${ac_tmp:=$tmp}"
        12350  +  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
 12330  12351   ' 0
 12331  12352     trap 'as_fn_exit 1' 1 2 13 15
 12332  12353   }
 12333  12354   # Create a (secure) tmp directory for tmp files.
 12334  12355   
 12335  12356   {
 12336  12357     tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
 12337         -  test -n "$tmp" && test -d "$tmp"
        12358  +  test -d "$tmp"
 12338  12359   }  ||
 12339  12360   {
 12340  12361     tmp=./conf$$-$RANDOM
 12341  12362     (umask 077 && mkdir "$tmp")
 12342  12363   } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
        12364  +ac_tmp=$tmp
 12343  12365   
 12344  12366   # Set up the scripts for CONFIG_FILES section.
 12345  12367   # No need to generate them if there are no CONFIG_FILES.
 12346  12368   # This happens for instance with `./config.status config.h'.
 12347  12369   if test -n "$CONFIG_FILES"; then
 12348  12370   
 12349  12371   
................................................................................
 12357  12379   ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' </dev/null 2>/dev/null`
 12358  12380   if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then
 12359  12381     ac_cs_awk_cr='\\r'
 12360  12382   else
 12361  12383     ac_cs_awk_cr=$ac_cr
 12362  12384   fi
 12363  12385   
 12364         -echo 'BEGIN {' >"$tmp/subs1.awk" &&
        12386  +echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
 12365  12387   _ACEOF
 12366  12388   
 12367  12389   
 12368  12390   {
 12369  12391     echo "cat >conf$$subs.awk <<_ACEOF" &&
 12370  12392     echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' &&
 12371  12393     echo "_ACEOF"
................................................................................
 12385  12407     else
 12386  12408       ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
 12387  12409     fi
 12388  12410   done
 12389  12411   rm -f conf$$subs.sh
 12390  12412   
 12391  12413   cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 12392         -cat >>"\$tmp/subs1.awk" <<\\_ACAWK &&
        12414  +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
 12393  12415   _ACEOF
 12394  12416   sed -n '
 12395  12417   h
 12396  12418   s/^/S["/; s/!.*/"]=/
 12397  12419   p
 12398  12420   g
 12399  12421   s/^[^!]*!//
................................................................................
 12433  12455     N
 12434  12456     s/\n//
 12435  12457   }
 12436  12458   ' >>$CONFIG_STATUS || ac_write_fail=1
 12437  12459   rm -f conf$$subs.awk
 12438  12460   cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 12439  12461   _ACAWK
 12440         -cat >>"\$tmp/subs1.awk" <<_ACAWK &&
        12462  +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
 12441  12463     for (key in S) S_is_set[key] = 1
 12442  12464     FS = ""
 12443  12465   
 12444  12466   }
 12445  12467   {
 12446  12468     line = $ 0
 12447  12469     nfields = split(line, field, "@")
................................................................................
 12465  12487   _ACAWK
 12466  12488   _ACEOF
 12467  12489   cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 12468  12490   if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
 12469  12491     sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
 12470  12492   else
 12471  12493     cat
 12472         -fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \
        12494  +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
 12473  12495     || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
 12474  12496   _ACEOF
 12475  12497   
 12476  12498   # VPATH may cause trouble with some makes, so we remove sole $(srcdir),
 12477  12499   # ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and
 12478  12500   # trailing colons and then remove the whole line if VPATH becomes empty
 12479  12501   # (actually we leave an empty line to preserve line numbers).
................................................................................
 12499  12521   cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 12500  12522   fi # test -n "$CONFIG_FILES"
 12501  12523   
 12502  12524   # Set up the scripts for CONFIG_HEADERS section.
 12503  12525   # No need to generate them if there are no CONFIG_HEADERS.
 12504  12526   # This happens for instance with `./config.status Makefile'.
 12505  12527   if test -n "$CONFIG_HEADERS"; then
 12506         -cat >"$tmp/defines.awk" <<\_ACAWK ||
        12528  +cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
 12507  12529   BEGIN {
 12508  12530   _ACEOF
 12509  12531   
 12510  12532   # Transform confdefs.h into an awk script `defines.awk', embedded as
 12511  12533   # here-document in config.status, that substitutes the proper values into
 12512  12534   # config.h.in to produce config.h.
 12513  12535   
 12514  12536   # Create a delimiter string that does not exist in confdefs.h, to ease
 12515  12537   # handling of long lines.
 12516  12538   ac_delim='%!_!# '
 12517  12539   for ac_last_try in false false :; do
 12518         -  ac_t=`sed -n "/$ac_delim/p" confdefs.h`
 12519         -  if test -z "$ac_t"; then
        12540  +  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
        12541  +  if test -z "$ac_tt"; then
 12520  12542       break
 12521  12543     elif $ac_last_try; then
 12522  12544       as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
 12523  12545     else
 12524  12546       ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
 12525  12547     fi
 12526  12548   done
................................................................................
 12613  12635   for ac_tag
 12614  12636   do
 12615  12637     case $ac_tag in
 12616  12638     :[FHLC]) ac_mode=$ac_tag; continue;;
 12617  12639     esac
 12618  12640     case $ac_mode$ac_tag in
 12619  12641     :[FHL]*:*);;
 12620         -  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;;
        12642  +  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
 12621  12643     :[FH]-) ac_tag=-:-;;
 12622  12644     :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
 12623  12645     esac
 12624  12646     ac_save_IFS=$IFS
 12625  12647     IFS=:
 12626  12648     set x $ac_tag
 12627  12649     IFS=$ac_save_IFS
................................................................................
 12632  12654     case $ac_mode in
 12633  12655     :L) ac_source=$1;;
 12634  12656     :[FH])
 12635  12657       ac_file_inputs=
 12636  12658       for ac_f
 12637  12659       do
 12638  12660         case $ac_f in
 12639         -      -) ac_f="$tmp/stdin";;
        12661  +      -) ac_f="$ac_tmp/stdin";;
 12640  12662         *) # Look for the file first in the build tree, then in the source tree
 12641  12663   	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
 12642  12664   	 # because $ac_f cannot contain `:'.
 12643  12665   	 test -f "$ac_f" ||
 12644  12666   	   case $ac_f in
 12645  12667   	   [\\/$]*) false;;
 12646  12668   	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
 12647  12669   	   esac ||
 12648         -	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;;
        12670  +	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
 12649  12671         esac
 12650  12672         case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
 12651  12673         as_fn_append ac_file_inputs " '$ac_f'"
 12652  12674       done
 12653  12675   
 12654  12676       # Let's still pretend it is `configure' which instantiates (i.e., don't
 12655  12677       # use $as_me), people would be surprised to read:
................................................................................
 12667  12689       *\&* | *\|* | *\\* )
 12668  12690          ac_sed_conf_input=`$as_echo "$configure_input" |
 12669  12691          sed 's/[\\\\&|]/\\\\&/g'`;; #(
 12670  12692       *) ac_sed_conf_input=$configure_input;;
 12671  12693       esac
 12672  12694   
 12673  12695       case $ac_tag in
 12674         -    *:-:* | *:-) cat >"$tmp/stdin" \
 12675         -      || as_fn_error $? "could not create $ac_file" "$LINENO" 5  ;;
        12696  +    *:-:* | *:-) cat >"$ac_tmp/stdin" \
        12697  +      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
 12676  12698       esac
 12677  12699       ;;
 12678  12700     esac
 12679  12701   
 12680  12702     ac_dir=`$as_dirname -- "$ac_file" ||
 12681  12703   $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
 12682  12704   	 X"$ac_file" : 'X\(//\)[^/]' \| \
................................................................................
 12798  12820   s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
 12799  12821   s&@builddir@&$ac_builddir&;t t
 12800  12822   s&@abs_builddir@&$ac_abs_builddir&;t t
 12801  12823   s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
 12802  12824   s&@INSTALL@&$ac_INSTALL&;t t
 12803  12825   $ac_datarootdir_hack
 12804  12826   "
 12805         -eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \
 12806         -  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
        12827  +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
        12828  +  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
 12807  12829   
 12808  12830   test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
 12809         -  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
 12810         -  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
        12831  +  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
        12832  +  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
        12833  +      "$ac_tmp/out"`; test -z "$ac_out"; } &&
 12811  12834     { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 12812  12835   which seems to be undefined.  Please make sure it is defined" >&5
 12813  12836   $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 12814  12837   which seems to be undefined.  Please make sure it is defined" >&2;}
 12815  12838   
 12816         -  rm -f "$tmp/stdin"
        12839  +  rm -f "$ac_tmp/stdin"
 12817  12840     case $ac_file in
 12818         -  -) cat "$tmp/out" && rm -f "$tmp/out";;
 12819         -  *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";;
        12841  +  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
        12842  +  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
 12820  12843     esac \
 12821  12844     || as_fn_error $? "could not create $ac_file" "$LINENO" 5
 12822  12845    ;;
 12823  12846     :H)
 12824  12847     #
 12825  12848     # CONFIG_HEADER
 12826  12849     #
 12827  12850     if test x"$ac_file" != x-; then
 12828  12851       {
 12829  12852         $as_echo "/* $configure_input  */" \
 12830         -      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs"
 12831         -    } >"$tmp/config.h" \
        12853  +      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
        12854  +    } >"$ac_tmp/config.h" \
 12832  12855         || as_fn_error $? "could not create $ac_file" "$LINENO" 5
 12833         -    if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then
        12856  +    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
 12834  12857         { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
 12835  12858   $as_echo "$as_me: $ac_file is unchanged" >&6;}
 12836  12859       else
 12837  12860         rm -f "$ac_file"
 12838         -      mv "$tmp/config.h" "$ac_file" \
        12861  +      mv "$ac_tmp/config.h" "$ac_file" \
 12839  12862   	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
 12840  12863       fi
 12841  12864     else
 12842  12865       $as_echo "/* $configure_input  */" \
 12843         -      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \
        12866  +      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
 12844  12867         || as_fn_error $? "could not create -" "$LINENO" 5
 12845  12868     fi
 12846  12869    ;;
 12847  12870   
 12848  12871     :C)  { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5
 12849  12872   $as_echo "$as_me: executing $ac_file commands" >&6;}
 12850  12873    ;;

Changes to configure.ac.

   123    123   #########
   124    124   # Check for needed/wanted headers
   125    125   AC_CHECK_HEADERS([sys/types.h stdlib.h stdint.h inttypes.h])
   126    126   
   127    127   #########
   128    128   # Figure out whether or not we have these functions
   129    129   #
   130         -AC_CHECK_FUNCS([usleep fdatasync localtime_r gmtime_r localtime_s utime])
          130  +AC_CHECK_FUNCS([usleep fdatasync localtime_r gmtime_r localtime_s utime malloc_usable_size])
   131    131   
   132    132   #########
   133    133   # By default, we use the amalgamation (this may be changed below...)
   134    134   #
   135    135   USE_AMALGAMATION=1
   136    136   
   137    137   #########

Changes to ext/fts3/fts3.c.

   708    708     ...                             /* Arguments for printf format string */
   709    709   ){
   710    710     if( *pRc==SQLITE_OK ){
   711    711       va_list ap;
   712    712       char *z;
   713    713       va_start(ap, zFormat);
   714    714       z = sqlite3_vmprintf(zFormat, ap);
          715  +    va_end(ap);
   715    716       if( z && *pz ){
   716    717         char *z2 = sqlite3_mprintf("%s%s", *pz, z);
   717    718         sqlite3_free(z);
   718    719         z = z2;
   719    720       }
   720    721       if( z==0 ) *pRc = SQLITE_NOMEM;
   721    722       sqlite3_free(*pz);

Changes to ext/fts3/fts3_write.c.

  1382   1382     sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
  1383   1383     sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
  1384   1384     sqlite3_int64 iEndBlock,        /* Final block of segment */
  1385   1385     const char *zRoot,              /* Buffer containing root node */
  1386   1386     int nRoot,                      /* Size of buffer containing root node */
  1387   1387     Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
  1388   1388   ){
  1389         -  int rc = SQLITE_OK;             /* Return code */
  1390   1389     Fts3SegReader *pReader;         /* Newly allocated SegReader object */
  1391   1390     int nExtra = 0;                 /* Bytes to allocate segment root node */
  1392   1391   
  1393   1392     assert( iStartLeaf<=iEndLeaf );
  1394   1393     if( iStartLeaf==0 ){
  1395   1394       nExtra = nRoot + FTS3_NODE_PADDING;
  1396   1395     }
................................................................................
  1410   1409       pReader->aNode = (char *)&pReader[1];
  1411   1410       pReader->nNode = nRoot;
  1412   1411       memcpy(pReader->aNode, zRoot, nRoot);
  1413   1412       memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  1414   1413     }else{
  1415   1414       pReader->iCurrentBlock = iStartLeaf-1;
  1416   1415     }
  1417         -
  1418         -  if( rc==SQLITE_OK ){
  1419         -    *ppReader = pReader;
  1420         -  }else{
  1421         -    sqlite3Fts3SegReaderFree(pReader);
  1422         -  }
  1423         -  return rc;
         1416  +  *ppReader = pReader;
         1417  +  return SQLITE_OK;
  1424   1418   }
  1425   1419   
  1426   1420   /*
  1427   1421   ** This is a comparison function used as a qsort() callback when sorting
  1428   1422   ** an array of pending terms by term. This occurs as part of flushing
  1429   1423   ** the contents of the pending-terms hash table to the database.
  1430   1424   */
................................................................................
  1466   1460     int iIndex,                     /* Index for p->aIndex */
  1467   1461     const char *zTerm,              /* Term to search for */
  1468   1462     int nTerm,                      /* Size of buffer zTerm */
  1469   1463     int bPrefix,                    /* True for a prefix iterator */
  1470   1464     Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
  1471   1465   ){
  1472   1466     Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
         1467  +  Fts3HashElem *pE;               /* Iterator variable */
  1473   1468     Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
  1474   1469     int nElem = 0;                  /* Size of array at aElem */
  1475   1470     int rc = SQLITE_OK;             /* Return Code */
  1476   1471     Fts3Hash *pHash;
  1477   1472   
  1478   1473     pHash = &p->aIndex[iIndex].hPending;
  1479   1474     if( bPrefix ){
  1480   1475       int nAlloc = 0;               /* Size of allocated array at aElem */
  1481         -    Fts3HashElem *pE = 0;         /* Iterator variable */
  1482   1476   
  1483   1477       for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  1484   1478         char *zKey = (char *)fts3HashKey(pE);
  1485   1479         int nKey = fts3HashKeysize(pE);
  1486   1480         if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  1487   1481           if( nElem==nAlloc ){
  1488   1482             Fts3HashElem **aElem2;
................................................................................
  1508   1502       */
  1509   1503       if( nElem>1 ){
  1510   1504         qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  1511   1505       }
  1512   1506   
  1513   1507     }else{
  1514   1508       /* The query is a simple term lookup that matches at most one term in
  1515         -    ** the index. All that is required is a straight hash-lookup. */
  1516         -    Fts3HashElem *pE = fts3HashFindElem(pHash, zTerm, nTerm);
         1509  +    ** the index. All that is required is a straight hash-lookup. 
         1510  +    **
         1511  +    ** Because the stack address of pE may be accessed via the aElem pointer
         1512  +    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
         1513  +    ** within this entire function, not just this "else{...}" block.
         1514  +    */
         1515  +    pE = fts3HashFindElem(pHash, zTerm, nTerm);
  1517   1516       if( pE ){
  1518   1517         aElem = &pE;
  1519   1518         nElem = 1;
  1520   1519       }
  1521   1520     }
  1522   1521   
  1523   1522     if( nElem>0 ){

Changes to ext/rtree/rtree.c.

  1189   1189   */
  1190   1190   static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  1191   1191     RtreeMatchArg *p;
  1192   1192     sqlite3_rtree_geometry *pGeom;
  1193   1193     int nBlob;
  1194   1194   
  1195   1195     /* Check that value is actually a blob. */
  1196         -  if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
         1196  +  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  1197   1197   
  1198   1198     /* Check that the blob is roughly the right size. */
  1199   1199     nBlob = sqlite3_value_bytes(pValue);
  1200   1200     if( nBlob<(int)sizeof(RtreeMatchArg) 
  1201   1201      || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
  1202   1202     ){
  1203   1203       return SQLITE_ERROR;

Changes to src/analyze.c.

   525    525         sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
   526    526       }
   527    527       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
   528    528       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
   529    529       sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
   530    530       sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
   531    531       sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
          532  +    sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
   532    533       sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
   533    534                         (char*)&stat3InitFuncdef, P4_FUNCDEF);
   534    535       sqlite3VdbeChangeP5(v, 2);
   535    536   #endif /* SQLITE_ENABLE_STAT3 */
   536    537   
   537    538       /* The block of memory cells initialized here is used as follows.
   538    539       **

Changes to src/backup.c.

   674    674     sqlite3BtreeEnter(pTo);
   675    675     sqlite3BtreeEnter(pFrom);
   676    676   
   677    677     assert( sqlite3BtreeIsInTrans(pTo) );
   678    678     pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
   679    679     if( pFd->pMethods ){
   680    680       i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
          681  +    sqlite3BeginBenignMalloc();
   681    682       sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
          683  +    sqlite3EndBenignMalloc();
   682    684     }
   683    685   
   684    686     /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
   685    687     ** to 0. This is used by the implementations of sqlite3_backup_step()
   686    688     ** and sqlite3_backup_finish() to detect that they are being called
   687    689     ** from this function, not directly by the user.
   688    690     */

Changes to src/btree.c.

   855    855   ** Given a btree page and a cell index (0 means the first cell on
   856    856   ** the page, 1 means the second cell, and so forth) return a pointer
   857    857   ** to the cell content.
   858    858   **
   859    859   ** This routine works only for pages that do not contain overflow cells.
   860    860   */
   861    861   #define findCell(P,I) \
   862         -  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
          862  +  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
   863    863   #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
   864    864   
   865    865   
   866    866   /*
   867    867   ** This a more complex version of findCell() that works for
   868    868   ** pages that do contain overflow cells.
   869    869   */
................................................................................
  1405   1405       data = pPage->aData;
  1406   1406       if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  1407   1407       assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  1408   1408       pPage->maskPage = (u16)(pBt->pageSize - 1);
  1409   1409       pPage->nOverflow = 0;
  1410   1410       usableSize = pBt->usableSize;
  1411   1411       pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
         1412  +    pPage->aDataEnd = &data[usableSize];
         1413  +    pPage->aCellIdx = &data[cellOffset];
  1412   1414       top = get2byteNotZero(&data[hdr+5]);
  1413   1415       pPage->nCell = get2byte(&data[hdr+3]);
  1414   1416       if( pPage->nCell>MX_CELL(pBt) ){
  1415   1417         /* To many cells for a single page.  The page must be corrupt */
  1416   1418         return SQLITE_CORRUPT_BKPT;
  1417   1419       }
  1418   1420       testcase( pPage->nCell==MX_CELL(pBt) );
................................................................................
  1508   1510     memset(&data[hdr+1], 0, 4);
  1509   1511     data[hdr+7] = 0;
  1510   1512     put2byte(&data[hdr+5], pBt->usableSize);
  1511   1513     pPage->nFree = (u16)(pBt->usableSize - first);
  1512   1514     decodeFlags(pPage, flags);
  1513   1515     pPage->hdrOffset = hdr;
  1514   1516     pPage->cellOffset = first;
         1517  +  pPage->aDataEnd = &data[pBt->usableSize];
         1518  +  pPage->aCellIdx = &data[first];
  1515   1519     pPage->nOverflow = 0;
  1516   1520     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  1517   1521     pPage->maskPage = (u16)(pBt->pageSize - 1);
  1518   1522     pPage->nCell = 0;
  1519   1523     pPage->isInit = 1;
  1520   1524   }
  1521   1525   
................................................................................
  1768   1772         char *zFullPathname = sqlite3Malloc(nFullPathname);
  1769   1773         MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  1770   1774         p->sharable = 1;
  1771   1775         if( !zFullPathname ){
  1772   1776           sqlite3_free(p);
  1773   1777           return SQLITE_NOMEM;
  1774   1778         }
  1775         -      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
         1779  +      rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
         1780  +      if( rc ){
         1781  +        sqlite3_free(zFullPathname);
         1782  +        sqlite3_free(p);
         1783  +        return rc;
         1784  +      }
  1776   1785   #if SQLITE_THREADSAFE
  1777   1786         mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  1778   1787         sqlite3_mutex_enter(mutexOpen);
  1779   1788         mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  1780   1789         sqlite3_mutex_enter(mutexShared);
  1781   1790   #endif
  1782   1791         for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
................................................................................
  3966   3975            && pBt->inTransaction==TRANS_READ                     /* (4) */
  3967   3976            && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
  3968   3977            && pBt->pPage1->aData[19]==0x01                       /* (5) */
  3969   3978           ){
  3970   3979             u8 aSave[4];
  3971   3980             u8 *aWrite = &pBuf[-4];
  3972   3981             memcpy(aSave, aWrite, 4);
  3973         -          rc = sqlite3OsRead(fd, aWrite, a+4, pBt->pageSize * (nextPage-1));
         3982  +          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  3974   3983             nextPage = get4byte(aWrite);
  3975   3984             memcpy(aWrite, aSave, 4);
  3976   3985           }else
  3977   3986   #endif
  3978   3987   
  3979   3988           {
  3980   3989             DbPage *pDbPage;
................................................................................
  4546   4555           ** page is less than 16384 bytes and may be stored as a 2-byte
  4547   4556           ** varint. This information is used to attempt to avoid parsing 
  4548   4557           ** the entire cell by checking for the cases where the record is 
  4549   4558           ** stored entirely within the b-tree page by inspecting the first 
  4550   4559           ** 2 bytes of the cell.
  4551   4560           */
  4552   4561           int nCell = pCell[0];
  4553         -        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
         4562  +        if( !(nCell & 0x80)
         4563  +         && nCell<=pPage->maxLocal
         4564  +         && (pCell+nCell+1)<=pPage->aDataEnd
         4565  +        ){
  4554   4566             /* This branch runs if the record-size field of the cell is a
  4555   4567             ** single byte varint and the record fits entirely on the main
  4556   4568             ** b-tree page.  */
         4569  +          testcase( pCell+nCell+1==pPage->aDataEnd );
  4557   4570             c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  4558   4571           }else if( !(pCell[1] & 0x80) 
  4559   4572             && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
         4573  +          && (pCell+nCell+2)<=pPage->aDataEnd
  4560   4574           ){
  4561   4575             /* The record-size field is a 2 byte varint and the record 
  4562   4576             ** fits entirely on the main b-tree page.  */
         4577  +          testcase( pCell+nCell+2==pPage->aDataEnd );
  4563   4578             c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  4564   4579           }else{
  4565   4580             /* The record flows over onto one or more overflow pages. In
  4566   4581             ** this case the whole cell needs to be parsed, a buffer allocated
  4567   4582             ** and accessPayload() used to retrieve the record into the
  4568   4583             ** buffer before VdbeRecordCompare() can be called. */
  4569   4584             void *pCellKey;
................................................................................
  5450   5465     if( *pRC ) return;
  5451   5466   
  5452   5467     assert( idx>=0 && idx<pPage->nCell );
  5453   5468     assert( sz==cellSize(pPage, idx) );
  5454   5469     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  5455   5470     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  5456   5471     data = pPage->aData;
  5457         -  ptr = &data[pPage->cellOffset + 2*idx];
         5472  +  ptr = &pPage->aCellIdx[2*idx];
  5458   5473     pc = get2byte(ptr);
  5459   5474     hdr = pPage->hdrOffset;
  5460   5475     testcase( pc==get2byte(&data[hdr+5]) );
  5461   5476     testcase( pc+sz==pPage->pBt->usableSize );
  5462   5477     if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  5463   5478       *pRC = SQLITE_CORRUPT_BKPT;
  5464   5479       return;
  5465   5480     }
  5466   5481     rc = freeSpace(pPage, pc, sz);
  5467   5482     if( rc ){
  5468   5483       *pRC = rc;
  5469   5484       return;
  5470   5485     }
  5471         -  endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
         5486  +  endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  5472   5487     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
  5473   5488     while( ptr<endPtr ){
  5474   5489       *(u16*)ptr = *(u16*)&ptr[2];
  5475   5490       ptr += 2;
  5476   5491     }
  5477   5492     pPage->nCell--;
  5478   5493     put2byte(&data[hdr+3], pPage->nCell);
................................................................................
  5606   5621               && (int)MX_CELL(pPage->pBt)<=10921);
  5607   5622     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  5608   5623   
  5609   5624     /* Check that the page has just been zeroed by zeroPage() */
  5610   5625     assert( pPage->nCell==0 );
  5611   5626     assert( get2byteNotZero(&data[hdr+5])==nUsable );
  5612   5627   
  5613         -  pCellptr = &data[pPage->cellOffset + nCell*2];
         5628  +  pCellptr = &pPage->aCellIdx[nCell*2];
  5614   5629     cellbody = nUsable;
  5615   5630     for(i=nCell-1; i>=0; i--){
  5616   5631       u16 sz = aSize[i];
  5617   5632       pCellptr -= 2;
  5618   5633       cellbody -= sz;
  5619   5634       put2byte(pCellptr, cellbody);
  5620   5635       memcpy(&data[cellbody], apCell[i], sz);
................................................................................
  6184   6199       szNew[i] = szRight;
  6185   6200       szNew[i-1] = szLeft;
  6186   6201     }
  6187   6202   
  6188   6203     /* Either we found one or more cells (cntnew[0])>0) or pPage is
  6189   6204     ** a virtual root page.  A virtual root page is when the real root
  6190   6205     ** page is page 1 and we are the only child of that page.
         6206  +  **
         6207  +  ** UPDATE:  The assert() below is not necessarily true if the database
         6208  +  ** file is corrupt.  The corruption will be detected and reported later
         6209  +  ** in this procedure so there is no need to act upon it now.
  6191   6210     */
         6211  +#if 0
  6192   6212     assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
         6213  +#endif
  6193   6214   
  6194   6215     TRACE(("BALANCE: old: %d %d %d  ",
  6195   6216       apOld[0]->pgno, 
  6196   6217       nOld>=2 ? apOld[1]->pgno : 0,
  6197   6218       nOld>=3 ? apOld[2]->pgno : 0
  6198   6219     ));
  6199   6220   

Changes to src/btreeInt.h.

   285    285     u16 maskPage;        /* Mask for page offset */
   286    286     struct _OvflCell {   /* Cells that will not fit on aData[] */
   287    287       u8 *pCell;          /* Pointers to the body of the overflow cell */
   288    288       u16 idx;            /* Insert this cell before idx-th non-overflow cell */
   289    289     } aOvfl[5];
   290    290     BtShared *pBt;       /* Pointer to BtShared that this page is part of */
   291    291     u8 *aData;           /* Pointer to disk image of the page data */
          292  +  u8 *aDataEnd;        /* One byte past the end of usable data */
          293  +  u8 *aCellIdx;        /* The cell index area */
   292    294     DbPage *pDbPage;     /* Pager page handle */
   293    295     Pgno pgno;           /* Page number for this page */
   294    296   };
   295    297   
   296    298   /*
   297    299   ** The in-memory image of a disk page has the auxiliary information appended
   298    300   ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
................................................................................
   364    366   #define TRANS_NONE  0
   365    367   #define TRANS_READ  1
   366    368   #define TRANS_WRITE 2
   367    369   
   368    370   /*
   369    371   ** An instance of this object represents a single database file.
   370    372   ** 
   371         -** A single database file can be in use as the same time by two
          373  +** A single database file can be in use at the same time by two
   372    374   ** or more database connections.  When two or more connections are
   373    375   ** sharing the same database file, each connection has it own
   374    376   ** private Btree object for the file and each of those Btrees points
   375    377   ** to this one BtShared object.  BtShared.nRef is the number of
   376    378   ** connections currently sharing this database file.
   377    379   **
   378    380   ** Fields in this structure are accessed under the BtShared.mutex
................................................................................
   470    472   /*
   471    473   ** A cursor is a pointer to a particular entry within a particular
   472    474   ** b-tree within a database file.
   473    475   **
   474    476   ** The entry is identified by its MemPage and the index in
   475    477   ** MemPage.aCell[] of the entry.
   476    478   **
   477         -** A single database file can shared by two more database connections,
          479  +** A single database file can be shared by two more database connections,
   478    480   ** but cursors cannot be shared.  Each cursor is associated with a
   479    481   ** particular database connection identified BtCursor.pBtree.db.
   480    482   **
   481    483   ** Fields in this structure are accessed under the BtShared.mutex
   482    484   ** found at self->pBt->mutex. 
   483    485   */
   484    486   struct BtCursor {
................................................................................
   631    633     int mxErr;        /* Stop accumulating errors when this reaches zero */
   632    634     int nErr;         /* Number of messages written to zErrMsg so far */
   633    635     int mallocFailed; /* A memory allocation error has occurred */
   634    636     StrAccum errMsg;  /* Accumulate the error message text here */
   635    637   };
   636    638   
   637    639   /*
   638         -** Read or write a two- and four-byte big-endian integer values.
          640  +** Routines to read or write a two- and four-byte big-endian integer values.
   639    641   */
   640    642   #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   641    643   #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   642    644   #define get4byte sqlite3Get4byte
   643    645   #define put4byte sqlite3Put4byte

Changes to src/build.c.

  2657   2657   
  2658   2658     /* 
  2659   2659     ** Allocate the index structure. 
  2660   2660     */
  2661   2661     nName = sqlite3Strlen30(zName);
  2662   2662     nCol = pList->nExpr;
  2663   2663     pIndex = sqlite3DbMallocZero(db, 
  2664         -      sizeof(Index) +              /* Index structure  */
  2665         -      sizeof(tRowcnt)*(nCol+1) +   /* Index.aiRowEst   */
  2666         -      sizeof(int)*nCol +           /* Index.aiColumn   */
  2667         -      sizeof(char *)*nCol +        /* Index.azColl     */
  2668         -      sizeof(u8)*nCol +            /* Index.aSortOrder */
  2669         -      nName + 1 +                  /* Index.zName      */
  2670         -      nExtra                       /* Collation sequence names */
         2664  +      ROUND8(sizeof(Index)) +              /* Index structure  */
         2665  +      ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
         2666  +      sizeof(char *)*nCol +                /* Index.azColl     */
         2667  +      sizeof(int)*nCol +                   /* Index.aiColumn   */
         2668  +      sizeof(u8)*nCol +                    /* Index.aSortOrder */
         2669  +      nName + 1 +                          /* Index.zName      */
         2670  +      nExtra                               /* Collation sequence names */
  2671   2671     );
  2672   2672     if( db->mallocFailed ){
  2673   2673       goto exit_create_index;
  2674   2674     }
  2675         -  pIndex->aiRowEst = (tRowcnt*)(&pIndex[1]);
  2676         -  pIndex->azColl = (char**)(&pIndex->aiRowEst[nCol+1]);
         2675  +  zExtra = (char*)pIndex;
         2676  +  pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
         2677  +  pIndex->azColl = (char**)
         2678  +     ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
         2679  +  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
         2680  +  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  2677   2681     pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  2678   2682     pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  2679   2683     pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  2680   2684     zExtra = (char *)(&pIndex->zName[nName+1]);
  2681   2685     memcpy(pIndex->zName, zName, nName+1);
  2682   2686     pIndex->pTable = pTab;
  2683   2687     pIndex->nColumn = pList->nExpr;

Changes to src/delete.c.

   144    144     SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
   145    145     Select *pSelect = NULL;      /* Complete SELECT tree */
   146    146   
   147    147     /* Check that there isn't an ORDER BY without a LIMIT clause.
   148    148     */
   149    149     if( pOrderBy && (pLimit == 0) ) {
   150    150       sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
   151         -    pParse->parseError = 1;
   152    151       goto limit_where_cleanup_2;
   153    152     }
   154    153   
   155    154     /* We only need to generate a select expression if there
   156    155     ** is a limit/offset term to enforce.
   157    156     */
   158    157     if( pLimit == 0 ) {

Changes to src/expr.c.

   866    866     for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
   867    867       Expr *pOldExpr = pOldItem->pExpr;
   868    868       pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
   869    869       pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   870    870       pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
   871    871       pItem->sortOrder = pOldItem->sortOrder;
   872    872       pItem->done = 0;
   873         -    pItem->iCol = pOldItem->iCol;
          873  +    pItem->iOrderByCol = pOldItem->iOrderByCol;
   874    874       pItem->iAlias = pOldItem->iAlias;
   875    875     }
   876    876     return pNew;
   877    877   }
   878    878   
   879    879   /*
   880    880   ** If cursors, triggers, views and subqueries are all omitted from
................................................................................
   936    936       struct IdList_item *pOldItem = &p->a[i];
   937    937       pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
   938    938       pNewItem->idx = pOldItem->idx;
   939    939     }
   940    940     return pNew;
   941    941   }
   942    942   Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
   943         -  Select *pNew;
          943  +  Select *pNew, *pPrior;
   944    944     if( p==0 ) return 0;
   945    945     pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
   946    946     if( pNew==0 ) return 0;
   947    947     pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
   948    948     pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
   949    949     pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
   950    950     pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
   951    951     pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
   952    952     pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
   953    953     pNew->op = p->op;
   954         -  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
          954  +  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
          955  +  if( pPrior ) pPrior->pNext = pNew;
          956  +  pNew->pNext = 0;
   955    957     pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
   956    958     pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
   957    959     pNew->iLimit = 0;
   958    960     pNew->iOffset = 0;
   959    961     pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
   960    962     pNew->pRightmost = 0;
   961    963     pNew->addrOpenEphm[0] = -1;
................................................................................
  1368   1370     if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
  1369   1371     pEList = p->pEList;
  1370   1372     if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
  1371   1373     if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  1372   1374     return 1;
  1373   1375   }
  1374   1376   #endif /* SQLITE_OMIT_SUBQUERY */
         1377  +
         1378  +/*
         1379  +** Code an OP_Once instruction and allocate space for its flag. Return the 
         1380  +** address of the new instruction.
         1381  +*/
         1382  +int sqlite3CodeOnce(Parse *pParse){
         1383  +  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
         1384  +  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
         1385  +}
  1375   1386   
  1376   1387   /*
  1377   1388   ** This function is used by the implementation of the IN (...) operator.
  1378   1389   ** It's job is to find or create a b-tree structure that may be used
  1379   1390   ** either to test for membership of the (...) set or to iterate through
  1380   1391   ** its members, skipping duplicates.
  1381   1392   **
................................................................................
  1429   1440   */
  1430   1441   #ifndef SQLITE_OMIT_SUBQUERY
  1431   1442   int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  1432   1443     Select *p;                            /* SELECT to the right of IN operator */
  1433   1444     int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
  1434   1445     int iTab = pParse->nTab++;            /* Cursor of the RHS table */
  1435   1446     int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
         1447  +  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
  1436   1448   
  1437   1449     assert( pX->op==TK_IN );
  1438   1450   
  1439   1451     /* Check to see if an existing table or index can be used to
  1440   1452     ** satisfy the query.  This is preferable to generating a new 
  1441   1453     ** ephemeral table.
  1442   1454     */
  1443   1455     p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  1444   1456     if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  1445   1457       sqlite3 *db = pParse->db;              /* Database connection */
  1446         -    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
  1447   1458       Table *pTab;                           /* Table <table>. */
  1448   1459       Expr *pExpr;                           /* Expression <column> */
  1449   1460       int iCol;                              /* Index of column <column> */
  1450   1461       int iDb;                               /* Database idx for pTab */
  1451   1462   
  1452   1463       assert( p );                        /* Because of isCandidateForInOpt(p) */
  1453   1464       assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
................................................................................
  1464   1475   
  1465   1476       /* This function is only called from two places. In both cases the vdbe
  1466   1477       ** has already been allocated. So assume sqlite3GetVdbe() is always
  1467   1478       ** successful here.
  1468   1479       */
  1469   1480       assert(v);
  1470   1481       if( iCol<0 ){
  1471         -      int iMem = ++pParse->nMem;
  1472   1482         int iAddr;
  1473   1483   
  1474         -      iAddr = sqlite3VdbeAddOp1(v, OP_Once, iMem);
         1484  +      iAddr = sqlite3CodeOnce(pParse);
  1475   1485   
  1476   1486         sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  1477   1487         eType = IN_INDEX_ROWID;
  1478   1488   
  1479   1489         sqlite3VdbeJumpHere(v, iAddr);
  1480   1490       }else{
  1481   1491         Index *pIdx;                         /* Iterator variable */
................................................................................
  1493   1503         int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
  1494   1504   
  1495   1505         for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  1496   1506           if( (pIdx->aiColumn[0]==iCol)
  1497   1507            && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  1498   1508            && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  1499   1509           ){
  1500         -          int iMem = ++pParse->nMem;
  1501   1510             int iAddr;
  1502   1511             char *pKey;
  1503   1512     
  1504   1513             pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  1505         -          iAddr = sqlite3VdbeAddOp1(v, OP_Once, iMem);
         1514  +          iAddr = sqlite3CodeOnce(pParse);
  1506   1515     
  1507   1516             sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  1508   1517                                  pKey,P4_KEYINFO_HANDOFF);
  1509   1518             VdbeComment((v, "%s", pIdx->zName));
  1510   1519             eType = IN_INDEX_INDEX;
  1511   1520   
  1512   1521             sqlite3VdbeJumpHere(v, iAddr);
  1513   1522             if( prNotFound && !pTab->aCol[iCol].notNull ){
  1514   1523               *prNotFound = ++pParse->nMem;
         1524  +            sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  1515   1525             }
  1516   1526           }
  1517   1527         }
  1518   1528       }
  1519   1529     }
  1520   1530   
  1521   1531     if( eType==0 ){
................................................................................
  1523   1533       ** We will have to generate an ephemeral table to do the job.
  1524   1534       */
  1525   1535       double savedNQueryLoop = pParse->nQueryLoop;
  1526   1536       int rMayHaveNull = 0;
  1527   1537       eType = IN_INDEX_EPH;
  1528   1538       if( prNotFound ){
  1529   1539         *prNotFound = rMayHaveNull = ++pParse->nMem;
         1540  +      sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  1530   1541       }else{
  1531   1542         testcase( pParse->nQueryLoop>(double)1 );
  1532   1543         pParse->nQueryLoop = (double)1;
  1533   1544         if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
  1534   1545           eType = IN_INDEX_ROWID;
  1535   1546         }
  1536   1547       }
................................................................................
  1595   1606     **    *  The right-hand side is a correlated subquery
  1596   1607     **    *  The right-hand side is an expression list containing variables
  1597   1608     **    *  We are inside a trigger
  1598   1609     **
  1599   1610     ** If all of the above are false, then we can run this code just once
  1600   1611     ** save the results, and reuse the same result on subsequent invocations.
  1601   1612     */
  1602         -  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
  1603         -    int mem = ++pParse->nMem;
  1604         -    testAddr = sqlite3VdbeAddOp1(v, OP_Once, mem);
         1613  +  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
         1614  +    testAddr = sqlite3CodeOnce(pParse);
  1605   1615     }
  1606   1616   
  1607   1617   #ifndef SQLITE_OMIT_EXPLAIN
  1608   1618     if( pParse->explain==2 ){
  1609   1619       char *zMsg = sqlite3MPrintf(
  1610   1620           pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  1611   1621           pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
................................................................................
  2935   2945       pExpr->iTable = iMem;
  2936   2946       pExpr->op2 = pExpr->op;
  2937   2947       pExpr->op = TK_REGISTER;
  2938   2948     }
  2939   2949     return inReg;
  2940   2950   }
  2941   2951   
         2952  +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
         2953  +/*
         2954  +** Generate a human-readable explanation of an expression tree.
         2955  +*/
         2956  +void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
         2957  +  int op;                   /* The opcode being coded */
         2958  +  const char *zBinOp = 0;   /* Binary operator */
         2959  +  const char *zUniOp = 0;   /* Unary operator */
         2960  +  if( pExpr==0 ){
         2961  +    op = TK_NULL;
         2962  +  }else{
         2963  +    op = pExpr->op;
         2964  +  }
         2965  +  switch( op ){
         2966  +    case TK_AGG_COLUMN: {
         2967  +      sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
         2968  +            pExpr->iTable, pExpr->iColumn);
         2969  +      break;
         2970  +    }
         2971  +    case TK_COLUMN: {
         2972  +      if( pExpr->iTable<0 ){
         2973  +        /* This only happens when coding check constraints */
         2974  +        sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
         2975  +      }else{
         2976  +        sqlite3ExplainPrintf(pOut, "{%d:%d}",
         2977  +                             pExpr->iTable, pExpr->iColumn);
         2978  +      }
         2979  +      break;
         2980  +    }
         2981  +    case TK_INTEGER: {
         2982  +      if( pExpr->flags & EP_IntValue ){
         2983  +        sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
         2984  +      }else{
         2985  +        sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
         2986  +      }
         2987  +      break;
         2988  +    }
         2989  +#ifndef SQLITE_OMIT_FLOATING_POINT
         2990  +    case TK_FLOAT: {
         2991  +      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
         2992  +      break;
         2993  +    }
         2994  +#endif
         2995  +    case TK_STRING: {
         2996  +      sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
         2997  +      break;
         2998  +    }
         2999  +    case TK_NULL: {
         3000  +      sqlite3ExplainPrintf(pOut,"NULL");
         3001  +      break;
         3002  +    }
         3003  +#ifndef SQLITE_OMIT_BLOB_LITERAL
         3004  +    case TK_BLOB: {
         3005  +      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
         3006  +      break;
         3007  +    }
         3008  +#endif
         3009  +    case TK_VARIABLE: {
         3010  +      sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
         3011  +                           pExpr->u.zToken, pExpr->iColumn);
         3012  +      break;
         3013  +    }
         3014  +    case TK_REGISTER: {
         3015  +      sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
         3016  +      break;
         3017  +    }
         3018  +    case TK_AS: {
         3019  +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
         3020  +      break;
         3021  +    }
         3022  +#ifndef SQLITE_OMIT_CAST
         3023  +    case TK_CAST: {
         3024  +      /* Expressions of the form:   CAST(pLeft AS token) */
         3025  +      const char *zAff = "unk";
         3026  +      switch( sqlite3AffinityType(pExpr->u.zToken) ){
         3027  +        case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
         3028  +        case SQLITE_AFF_NONE:    zAff = "NONE";     break;
         3029  +        case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
         3030  +        case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
         3031  +        case SQLITE_AFF_REAL:    zAff = "REAL";     break;
         3032  +      }
         3033  +      sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
         3034  +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
         3035  +      sqlite3ExplainPrintf(pOut, ")");
         3036  +      break;
         3037  +    }
         3038  +#endif /* SQLITE_OMIT_CAST */
         3039  +    case TK_LT:      zBinOp = "LT";     break;
         3040  +    case TK_LE:      zBinOp = "LE";     break;
         3041  +    case TK_GT:      zBinOp = "GT";     break;
         3042  +    case TK_GE:      zBinOp = "GE";     break;
         3043  +    case TK_NE:      zBinOp = "NE";     break;
         3044  +    case TK_EQ:      zBinOp = "EQ";     break;
         3045  +    case TK_IS:      zBinOp = "IS";     break;
         3046  +    case TK_ISNOT:   zBinOp = "ISNOT";  break;
         3047  +    case TK_AND:     zBinOp = "AND";    break;
         3048  +    case TK_OR:      zBinOp = "OR";     break;
         3049  +    case TK_PLUS:    zBinOp = "ADD";    break;
         3050  +    case TK_STAR:    zBinOp = "MUL";    break;
         3051  +    case TK_MINUS:   zBinOp = "SUB";    break;
         3052  +    case TK_REM:     zBinOp = "REM";    break;
         3053  +    case TK_BITAND:  zBinOp = "BITAND"; break;
         3054  +    case TK_BITOR:   zBinOp = "BITOR";  break;
         3055  +    case TK_SLASH:   zBinOp = "DIV";    break;
         3056  +    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
         3057  +    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
         3058  +    case TK_CONCAT:  zBinOp = "CONCAT"; break;
         3059  +
         3060  +    case TK_UMINUS:  zUniOp = "UMINUS"; break;
         3061  +    case TK_UPLUS:   zUniOp = "UPLUS";  break;
         3062  +    case TK_BITNOT:  zUniOp = "BITNOT"; break;
         3063  +    case TK_NOT:     zUniOp = "NOT";    break;
         3064  +    case TK_ISNULL:  zUniOp = "ISNULL"; break;
         3065  +    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
         3066  +
         3067  +    case TK_AGG_FUNCTION:
         3068  +    case TK_CONST_FUNC:
         3069  +    case TK_FUNCTION: {
         3070  +      ExprList *pFarg;       /* List of function arguments */
         3071  +      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
         3072  +        pFarg = 0;
         3073  +      }else{
         3074  +        pFarg = pExpr->x.pList;
         3075  +      }
         3076  +      sqlite3ExplainPrintf(pOut, "%sFUNCTION:%s(",
         3077  +                           op==TK_AGG_FUNCTION ? "AGG_" : "",
         3078  +                           pExpr->u.zToken);
         3079  +      if( pFarg ){
         3080  +        sqlite3ExplainExprList(pOut, pFarg);
         3081  +      }
         3082  +      sqlite3ExplainPrintf(pOut, ")");
         3083  +      break;
         3084  +    }
         3085  +#ifndef SQLITE_OMIT_SUBQUERY
         3086  +    case TK_EXISTS: {
         3087  +      sqlite3ExplainPrintf(pOut, "EXISTS(");
         3088  +      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
         3089  +      sqlite3ExplainPrintf(pOut,")");
         3090  +      break;
         3091  +    }
         3092  +    case TK_SELECT: {
         3093  +      sqlite3ExplainPrintf(pOut, "(");
         3094  +      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
         3095  +      sqlite3ExplainPrintf(pOut, ")");
         3096  +      break;
         3097  +    }
         3098  +    case TK_IN: {
         3099  +      sqlite3ExplainPrintf(pOut, "IN(");
         3100  +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
         3101  +      sqlite3ExplainPrintf(pOut, ",");
         3102  +      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
         3103  +        sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
         3104  +      }else{
         3105  +        sqlite3ExplainExprList(pOut, pExpr->x.pList);
         3106  +      }
         3107  +      sqlite3ExplainPrintf(pOut, ")");
         3108  +      break;
         3109  +    }
         3110  +#endif /* SQLITE_OMIT_SUBQUERY */
         3111  +
         3112  +    /*
         3113  +    **    x BETWEEN y AND z
         3114  +    **
         3115  +    ** This is equivalent to
         3116  +    **
         3117  +    **    x>=y AND x<=z
         3118  +    **
         3119  +    ** X is stored in pExpr->pLeft.
         3120  +    ** Y is stored in pExpr->pList->a[0].pExpr.
         3121  +    ** Z is stored in pExpr->pList->a[1].pExpr.
         3122  +    */
         3123  +    case TK_BETWEEN: {
         3124  +      Expr *pX = pExpr->pLeft;
         3125  +      Expr *pY = pExpr->x.pList->a[0].pExpr;
         3126  +      Expr *pZ = pExpr->x.pList->a[1].pExpr;
         3127  +      sqlite3ExplainPrintf(pOut, "BETWEEN(");
         3128  +      sqlite3ExplainExpr(pOut, pX);
         3129  +      sqlite3ExplainPrintf(pOut, ",");
         3130  +      sqlite3ExplainExpr(pOut, pY);
         3131  +      sqlite3ExplainPrintf(pOut, ",");
         3132  +      sqlite3ExplainExpr(pOut, pZ);
         3133  +      sqlite3ExplainPrintf(pOut, ")");
         3134  +      break;
         3135  +    }
         3136  +    case TK_TRIGGER: {
         3137  +      /* If the opcode is TK_TRIGGER, then the expression is a reference
         3138  +      ** to a column in the new.* or old.* pseudo-tables available to
         3139  +      ** trigger programs. In this case Expr.iTable is set to 1 for the
         3140  +      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
         3141  +      ** is set to the column of the pseudo-table to read, or to -1 to
         3142  +      ** read the rowid field.
         3143  +      */
         3144  +      sqlite3ExplainPrintf(pOut, "%s(%d)", 
         3145  +          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
         3146  +      break;
         3147  +    }
         3148  +    case TK_CASE: {
         3149  +      sqlite3ExplainPrintf(pOut, "CASE(");
         3150  +      sqlite3ExplainExpr(pOut, pExpr->pLeft);
         3151  +      sqlite3ExplainPrintf(pOut, ",");
         3152  +      sqlite3ExplainExprList(pOut, pExpr->x.pList);
         3153  +      break;
         3154  +    }
         3155  +#ifndef SQLITE_OMIT_TRIGGER
         3156  +    case TK_RAISE: {
         3157  +      const char *zType = "unk";
         3158  +      switch( pExpr->affinity ){
         3159  +        case OE_Rollback:   zType = "rollback";  break;
         3160  +        case OE_Abort:      zType = "abort";     break;
         3161  +        case OE_Fail:       zType = "fail";      break;
         3162  +        case OE_Ignore:     zType = "ignore";    break;
         3163  +      }
         3164  +      sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
         3165  +      break;
         3166  +    }
         3167  +#endif
         3168  +  }
         3169  +  if( zBinOp ){
         3170  +    sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
         3171  +    sqlite3ExplainExpr(pOut, pExpr->pLeft);
         3172  +    sqlite3ExplainPrintf(pOut,",");
         3173  +    sqlite3ExplainExpr(pOut, pExpr->pRight);
         3174  +    sqlite3ExplainPrintf(pOut,")");
         3175  +  }else if( zUniOp ){
         3176  +    sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
         3177  +    sqlite3ExplainExpr(pOut, pExpr->pLeft);
         3178  +    sqlite3ExplainPrintf(pOut,")");
         3179  +  }
         3180  +}
         3181  +#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
         3182  +
         3183  +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
         3184  +/*
         3185  +** Generate a human-readable explanation of an expression list.
         3186  +*/
         3187  +void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
         3188  +  int i;
         3189  +  if( pList==0 || pList->nExpr==0 ){
         3190  +    sqlite3ExplainPrintf(pOut, "(empty-list)");
         3191  +    return;
         3192  +  }else if( pList->nExpr==1 ){
         3193  +    sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
         3194  +  }else{
         3195  +    sqlite3ExplainPush(pOut);
         3196  +    for(i=0; i<pList->nExpr; i++){
         3197  +      sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
         3198  +      sqlite3ExplainPush(pOut);
         3199  +      sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
         3200  +      sqlite3ExplainPop(pOut);
         3201  +      if( i<pList->nExpr-1 ){
         3202  +        sqlite3ExplainNL(pOut);
         3203  +      }
         3204  +    }
         3205  +    sqlite3ExplainPop(pOut);
         3206  +  }
         3207  +}
         3208  +#endif /* SQLITE_DEBUG */
         3209  +
  2942   3210   /*
  2943   3211   ** Return TRUE if pExpr is an constant expression that is appropriate
  2944   3212   ** for factoring out of a loop.  Appropriate expressions are:
  2945   3213   **
  2946   3214   **    *  Any expression that evaluates to two or more opcodes.
  2947   3215   **
  2948   3216   **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
................................................................................
  3758   4026   void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  3759   4027     sqlite3ExprCacheRemove(pParse, iReg, nReg);
  3760   4028     if( nReg>pParse->nRangeReg ){
  3761   4029       pParse->nRangeReg = nReg;
  3762   4030       pParse->iRangeReg = iReg;
  3763   4031     }
  3764   4032   }
         4033  +
         4034  +/*
         4035  +** Mark all temporary registers as being unavailable for reuse.
         4036  +*/
         4037  +void sqlite3ClearTempRegCache(Parse *pParse){
         4038  +  pParse->nTempReg = 0;
         4039  +  pParse->nRangeReg = 0;
         4040  +}

Changes to src/global.c.

   143    143      SQLITE_THREADSAFE==1,      /* bFullMutex */
   144    144      SQLITE_USE_URI,            /* bOpenUri */
   145    145      0x7ffffffe,                /* mxStrlen */
   146    146      128,                       /* szLookaside */
   147    147      500,                       /* nLookaside */
   148    148      {0,0,0,0,0,0,0,0},         /* m */
   149    149      {0,0,0,0,0,0,0,0,0},       /* mutex */
   150         -   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
          150  +   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
   151    151      (void*)0,                  /* pHeap */
   152    152      0,                         /* nHeap */
   153    153      0, 0,                      /* mnHeap, mxHeap */
   154    154      (void*)0,                  /* pScratch */
   155    155      0,                         /* szScratch */
   156    156      0,                         /* nScratch */
   157    157      (void*)0,                  /* pPage */

Changes to src/insert.c.

    43     43   **  ------------------------------
    44     44   **  'a'            TEXT
    45     45   **  'b'            NONE
    46     46   **  'c'            NUMERIC
    47     47   **  'd'            INTEGER
    48     48   **  'e'            REAL
    49     49   **
    50         -** An extra 'b' is appended to the end of the string to cover the
           50  +** An extra 'd' is appended to the end of the string to cover the
    51     51   ** rowid that appears as the last column in every index.
    52     52   **
    53     53   ** Memory for the buffer containing the column index affinity string
    54     54   ** is managed along with the rest of the Index structure. It will be
    55     55   ** released when sqlite3DeleteIndex() is called.
    56     56   */
    57     57   const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
................................................................................
    71     71       if( !pIdx->zColAff ){
    72     72         db->mallocFailed = 1;
    73     73         return 0;
    74     74       }
    75     75       for(n=0; n<pIdx->nColumn; n++){
    76     76         pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
    77     77       }
    78         -    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
           78  +    pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
    79     79       pIdx->zColAff[n] = 0;
    80     80     }
    81     81    
    82     82     return pIdx->zColAff;
    83     83   }
    84     84   
    85     85   /*
................................................................................
   235    235   
   236    236     assert( v );   /* We failed long ago if this is not so */
   237    237     for(p = pParse->pAinc; p; p = p->pNext){
   238    238       pDb = &db->aDb[p->iDb];
   239    239       memId = p->regCtr;
   240    240       assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   241    241       sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
          242  +    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
   242    243       addr = sqlite3VdbeCurrentAddr(v);
   243    244       sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   244    245       sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
   245    246       sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   246    247       sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
   247    248       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   248    249       sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
................................................................................
  1102   1103   **                                return code of SQLITE_CONSTRAINT.
  1103   1104   **
  1104   1105   **  any              ABORT        Back out changes from the current command
  1105   1106   **                                only (do not do a complete rollback) then
  1106   1107   **                                cause sqlite3_exec() to return immediately
  1107   1108   **                                with SQLITE_CONSTRAINT.
  1108   1109   **
  1109         -**  any              FAIL         Sqlite_exec() returns immediately with a
         1110  +**  any              FAIL         Sqlite3_exec() returns immediately with a
  1110   1111   **                                return code of SQLITE_CONSTRAINT.  The
  1111   1112   **                                transaction is not rolled back and any
  1112   1113   **                                prior changes are retained.
  1113   1114   **
  1114   1115   **  any              IGNORE       The record number and data is popped from
  1115   1116   **                                the stack and there is an immediate jump
  1116   1117   **                                to label ignoreDest.
................................................................................
  1584   1585   }
  1585   1586   
  1586   1587   /*
  1587   1588   ** Attempt the transfer optimization on INSERTs of the form
  1588   1589   **
  1589   1590   **     INSERT INTO tab1 SELECT * FROM tab2;
  1590   1591   **
  1591         -** This optimization is only attempted if
  1592         -**
  1593         -**    (1)  tab1 and tab2 have identical schemas including all the
  1594         -**         same indices and constraints
         1592  +** The xfer optimization transfers raw records from tab2 over to tab1.  
         1593  +** Columns are not decoded and reassemblied, which greatly improves
         1594  +** performance.  Raw index records are transferred in the same way.
  1595   1595   **
  1596         -**    (2)  tab1 and tab2 are different tables
         1596  +** The xfer optimization is only attempted if tab1 and tab2 are compatible.
         1597  +** There are lots of rules for determining compatibility - see comments
         1598  +** embedded in the code for details.
  1597   1599   **
  1598         -**    (3)  There must be no triggers on tab1
  1599         -**
  1600         -**    (4)  The result set of the SELECT statement is "*"
  1601         -**
  1602         -**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
  1603         -**         or LIMIT clause.
         1600  +** This routine returns TRUE if the optimization is guaranteed to be used.
         1601  +** Sometimes the xfer optimization will only work if the destination table
         1602  +** is empty - a factor that can only be determined at run-time.  In that
         1603  +** case, this routine generates code for the xfer optimization but also
         1604  +** does a test to see if the destination table is empty and jumps over the
         1605  +** xfer optimization code if the test fails.  In that case, this routine
         1606  +** returns FALSE so that the caller will know to go ahead and generate
         1607  +** an unoptimized transfer.  This routine also returns FALSE if there
         1608  +** is no chance that the xfer optimization can be applied.
  1604   1609   **
  1605         -**    (6)  The SELECT statement is a simple (not a compound) select that
  1606         -**         contains only tab2 in its FROM clause
  1607         -**
  1608         -** This method for implementing the INSERT transfers raw records from
  1609         -** tab2 over to tab1.  The columns are not decoded.  Raw records from
  1610         -** the indices of tab2 are transfered to tab1 as well.  In so doing,
  1611         -** the resulting tab1 has much less fragmentation.
  1612         -**
  1613         -** This routine returns TRUE if the optimization is attempted.  If any
  1614         -** of the conditions above fail so that the optimization should not
  1615         -** be attempted, then this routine returns FALSE.
         1610  +** This optimization is particularly useful at making VACUUM run faster.
  1616   1611   */
  1617   1612   static int xferOptimization(
  1618   1613     Parse *pParse,        /* Parser context */
  1619   1614     Table *pDest,         /* The table we are inserting into */
  1620   1615     Select *pSelect,      /* A SELECT statement to use as the data source */
  1621   1616     int onError,          /* How to handle constraint errors */
  1622   1617     int iDbDest           /* The database of pDest */
................................................................................
  1645   1640     }
  1646   1641   #ifndef SQLITE_OMIT_VIRTUALTABLE
  1647   1642     if( pDest->tabFlags & TF_Virtual ){
  1648   1643       return 0;   /* tab1 must not be a virtual table */
  1649   1644     }
  1650   1645   #endif
  1651   1646     if( onError==OE_Default ){
  1652         -    onError = OE_Abort;
  1653         -  }
  1654         -  if( onError!=OE_Abort && onError!=OE_Rollback ){
  1655         -    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
         1647  +    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
         1648  +    if( onError==OE_Default ) onError = OE_Abort;
  1656   1649     }
  1657   1650     assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
  1658   1651     if( pSelect->pSrc->nSrc!=1 ){
  1659   1652       return 0;   /* FROM clause must have exactly one term */
  1660   1653     }
  1661   1654     if( pSelect->pSrc->a[0].pSelect ){
  1662   1655       return 0;   /* FROM clause cannot contain a subquery */
................................................................................
  1754   1747     ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  1755   1748     */
  1756   1749     if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  1757   1750       return 0;
  1758   1751     }
  1759   1752   #endif
  1760   1753     if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  1761         -    return 0;
         1754  +    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
  1762   1755     }
  1763   1756   
  1764         -  /* If we get this far, it means either:
  1765         -  **
  1766         -  **    *   We can always do the transfer if the table contains an
  1767         -  **        an integer primary key
  1768         -  **
  1769         -  **    *   We can conditionally do the transfer if the destination
  1770         -  **        table is empty.
         1757  +  /* If we get this far, it means that the xfer optimization is at
         1758  +  ** least a possibility, though it might only work if the destination
         1759  +  ** table (tab1) is initially empty.
  1771   1760     */
  1772   1761   #ifdef SQLITE_TEST
  1773   1762     sqlite3_xferopt_count++;
  1774   1763   #endif
  1775   1764     iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  1776   1765     v = sqlite3GetVdbe(pParse);
  1777   1766     sqlite3CodeVerifySchema(pParse, iDbSrc);
  1778   1767     iSrc = pParse->nTab++;
  1779   1768     iDest = pParse->nTab++;
  1780   1769     regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  1781   1770     sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  1782         -  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
  1783         -    /* If tables do not have an INTEGER PRIMARY KEY and there
  1784         -    ** are indices to be copied and the destination is not empty,
  1785         -    ** we have to disallow the transfer optimization because the
  1786         -    ** the rowids might change which will mess up indexing.
         1771  +  if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
         1772  +   || destHasUniqueIdx                              /* (2) */
         1773  +   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
         1774  +  ){
         1775  +    /* In some circumstances, we are able to run the xfer optimization
         1776  +    ** only if the destination table is initially empty.  This code makes
         1777  +    ** that determination.  Conditions under which the destination must
         1778  +    ** be empty:
         1779  +    **
         1780  +    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
         1781  +    **     (If the destination is not initially empty, the rowid fields
         1782  +    **     of index entries might need to change.)
         1783  +    **
         1784  +    ** (2) The destination has a unique index.  (The xfer optimization 
         1785  +    **     is unable to test uniqueness.)
  1787   1786       **
  1788         -    ** Or if the destination has a UNIQUE index and is not empty,
  1789         -    ** we also disallow the transfer optimization because we cannot
  1790         -    ** insure that all entries in the union of DEST and SRC will be
  1791         -    ** unique.
         1787  +    ** (3) onError is something other than OE_Abort and OE_Rollback.
  1792   1788       */
  1793   1789       addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  1794   1790       emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  1795   1791       sqlite3VdbeJumpHere(v, addr1);
  1796   1792     }else{
  1797   1793       emptyDestTest = 0;
  1798   1794     }

Changes to src/loadext.c.

   621    621   ** Load all automatic extensions.
   622    622   **
   623    623   ** If anything goes wrong, set an error in the database connection.
   624    624   */
   625    625   void sqlite3AutoLoadExtensions(sqlite3 *db){
   626    626     int i;
   627    627     int go = 1;
          628  +  int rc;
   628    629     int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
   629    630   
   630    631     wsdAutoextInit;
   631    632     if( wsdAutoext.nExt==0 ){
   632    633       /* Common case: early out without every having to acquire a mutex */
   633    634       return;
   634    635     }
................................................................................
   643    644         go = 0;
   644    645       }else{
   645    646         xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
   646    647                 wsdAutoext.aExt[i];
   647    648       }
   648    649       sqlite3_mutex_leave(mutex);
   649    650       zErrmsg = 0;
   650         -    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
   651         -      sqlite3Error(db, SQLITE_ERROR,
          651  +    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
          652  +      sqlite3Error(db, rc,
   652    653               "automatic extension loading failed: %s", zErrmsg);
   653    654         go = 0;
   654    655       }
   655    656       sqlite3_free(zErrmsg);
   656    657     }
   657    658   }

Changes to src/main.c.

    45     45   const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
    46     46   
    47     47   /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
    48     48   ** returns an integer equal to SQLITE_VERSION_NUMBER.
    49     49   */
    50     50   int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
    51     51   
    52         -/* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
    53         -** zero if and only if SQLite was compiled mutexing code omitted due to
           52  +/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
           53  +** zero if and only if SQLite was compiled with mutexing code omitted due to
    54     54   ** the SQLITE_THREADSAFE compile-time option being set to 0.
    55     55   */
    56     56   int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
    57     57   
    58     58   #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
    59     59   /*
    60     60   ** If the following function pointer is not NULL and if
................................................................................
   235    235   #endif
   236    236   
   237    237     /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
   238    238     ** compile-time option.
   239    239     */
   240    240   #ifdef SQLITE_EXTRA_INIT
   241    241     if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
   242         -    int SQLITE_EXTRA_INIT(void);
   243         -    rc = SQLITE_EXTRA_INIT();
          242  +    int SQLITE_EXTRA_INIT(const char*);
          243  +    rc = SQLITE_EXTRA_INIT(0);
   244    244     }
   245    245   #endif
   246    246   
   247    247     return rc;
   248    248   }
   249    249   
   250    250   /*
................................................................................
   253    253   ** while any part of SQLite is otherwise in use in any thread.  This
   254    254   ** routine is not threadsafe.  But it is safe to invoke this routine
   255    255   ** on when SQLite is already shut down.  If SQLite is already shut down
   256    256   ** when this routine is invoked, then this routine is a harmless no-op.
   257    257   */
   258    258   int sqlite3_shutdown(void){
   259    259     if( sqlite3GlobalConfig.isInit ){
          260  +#ifdef SQLITE_EXTRA_SHUTDOWN
          261  +    void SQLITE_EXTRA_SHUTDOWN(void);
          262  +    SQLITE_EXTRA_SHUTDOWN();
          263  +#endif
   260    264       sqlite3_os_end();
   261    265       sqlite3_reset_auto_extension();
   262    266       sqlite3GlobalConfig.isInit = 0;
   263    267     }
   264    268     if( sqlite3GlobalConfig.isPCacheInit ){
   265    269       sqlite3PcacheShutdown();
   266    270       sqlite3GlobalConfig.isPCacheInit = 0;
................................................................................
   361    365         sqlite3GlobalConfig.pPage = va_arg(ap, void*);
   362    366         sqlite3GlobalConfig.szPage = va_arg(ap, int);
   363    367         sqlite3GlobalConfig.nPage = va_arg(ap, int);
   364    368         break;
   365    369       }
   366    370   
   367    371       case SQLITE_CONFIG_PCACHE: {
   368         -      /* Specify an alternative page cache implementation */
   369         -      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
          372  +      /* no-op */
   370    373         break;
   371    374       }
   372         -
   373    375       case SQLITE_CONFIG_GETPCACHE: {
   374         -      if( sqlite3GlobalConfig.pcache.xInit==0 ){
          376  +      /* now an error */
          377  +      rc = SQLITE_ERROR;
          378  +      break;
          379  +    }
          380  +
          381  +    case SQLITE_CONFIG_PCACHE2: {
          382  +      /* Specify an alternative page cache implementation */
          383  +      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
          384  +      break;
          385  +    }
          386  +    case SQLITE_CONFIG_GETPCACHE2: {
          387  +      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   375    388           sqlite3PCacheSetDefault();
   376    389         }
   377         -      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
          390  +      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
   378    391         break;
   379    392       }
   380    393   
   381    394   #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
   382    395       case SQLITE_CONFIG_HEAP: {
   383    396         /* Designate a buffer for heap memory space */
   384    397         sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
................................................................................
   469    482     /* Free any existing lookaside buffer for this handle before
   470    483     ** allocating a new one so we don't have to have space for 
   471    484     ** both at the same time.
   472    485     */
   473    486     if( db->lookaside.bMalloced ){
   474    487       sqlite3_free(db->lookaside.pStart);
   475    488     }
   476         -  /* The size of a lookaside slot needs to be larger than a pointer
   477         -  ** to be useful.
          489  +  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
          490  +  ** than a pointer to be useful.
   478    491     */
          492  +  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
   479    493     if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
   480    494     if( cnt<0 ) cnt = 0;
   481    495     if( sz==0 || cnt==0 ){
   482    496       sz = 0;
   483    497       pStart = 0;
   484    498     }else if( pBuf==0 ){
   485         -    sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
   486    499       sqlite3BeginBenignMalloc();
   487    500       pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
   488    501       sqlite3EndBenignMalloc();
          502  +    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
   489    503     }else{
   490         -    sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
   491    504       pStart = pBuf;
   492    505     }
   493    506     db->lookaside.pStart = pStart;
   494    507     db->lookaside.pFree = 0;
   495    508     db->lookaside.sz = (u16)sz;
   496    509     if( pStart ){
   497    510       int i;
................................................................................
   516    529   
   517    530   /*
   518    531   ** Return the mutex associated with a database connection.
   519    532   */
   520    533   sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
   521    534     return db->mutex;
   522    535   }
          536  +
          537  +/*
          538  +** Free up as much memory as we can from the given database
          539  +** connection.
          540  +*/
          541  +int sqlite3_db_release_memory(sqlite3 *db){
          542  +  int i;
          543  +  sqlite3_mutex_enter(db->mutex);
          544  +  sqlite3BtreeEnterAll(db);
          545  +  for(i=0; i<db->nDb; i++){
          546  +    Btree *pBt = db->aDb[i].pBt;
          547  +    if( pBt ){
          548  +      Pager *pPager = sqlite3BtreePager(pBt);
          549  +      sqlite3PagerShrink(pPager);
          550  +    }
          551  +  }
          552  +  sqlite3BtreeLeaveAll(db);
          553  +  sqlite3_mutex_leave(db->mutex);
          554  +  return SQLITE_OK;
          555  +}
   523    556   
   524    557   /*
   525    558   ** Configuration settings for an individual database connection
   526    559   */
   527    560   int sqlite3_db_config(sqlite3 *db, int op, ...){
   528    561     va_list ap;
   529    562     int rc;
................................................................................
  1645   1678   ** Create a new collating function for database "db".  The name is zName
  1646   1679   ** and the encoding is enc.
  1647   1680   */
  1648   1681   static int createCollation(
  1649   1682     sqlite3* db,
  1650   1683     const char *zName, 
  1651   1684     u8 enc,
  1652         -  u8 collType,
  1653   1685     void* pCtx,
  1654   1686     int(*xCompare)(void*,int,const void*,int,const void*),
  1655   1687     void(*xDel)(void*)
  1656   1688   ){
  1657   1689     CollSeq *pColl;
  1658   1690     int enc2;
  1659   1691     int nName = sqlite3Strlen30(zName);
................................................................................
  1710   1742   
  1711   1743     pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  1712   1744     if( pColl==0 ) return SQLITE_NOMEM;
  1713   1745     pColl->xCmp = xCompare;
  1714   1746     pColl->pUser = pCtx;
  1715   1747     pColl->xDel = xDel;
  1716   1748     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  1717         -  pColl->type = collType;
  1718   1749     sqlite3Error(db, SQLITE_OK, 0);
  1719   1750     return SQLITE_OK;
  1720   1751   }
  1721   1752   
  1722   1753   
  1723   1754   /*
  1724   1755   ** This array defines hard upper bounds on limit values.  The
................................................................................
  2171   2202     sqlite3HashInit(&db->aModule);
  2172   2203   #endif
  2173   2204   
  2174   2205     /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  2175   2206     ** and UTF-16, so add a version for each to avoid any unnecessary
  2176   2207     ** conversions. The only error that can occur here is a malloc() failure.
  2177   2208     */
  2178         -  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
  2179         -                  binCollFunc, 0);
  2180         -  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
  2181         -                  binCollFunc, 0);
  2182         -  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
  2183         -                  binCollFunc, 0);
  2184         -  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
  2185         -                  binCollFunc, 0);
         2209  +  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
         2210  +  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
         2211  +  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
         2212  +  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  2186   2213     if( db->mallocFailed ){
  2187   2214       goto opendb_out;
  2188   2215     }
  2189   2216     db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  2190   2217     assert( db->pDfltColl!=0 );
  2191   2218   
  2192   2219     /* Also add a UTF-8 case-insensitive collation sequence. */
  2193         -  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
  2194         -                  nocaseCollatingFunc, 0);
         2220  +  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  2195   2221   
  2196   2222     /* Parse the filename/URI argument. */
  2197   2223     db->openFlags = flags;
  2198   2224     rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  2199   2225     if( rc!=SQLITE_OK ){
  2200   2226       if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  2201   2227       sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
................................................................................
  2236   2262     */
  2237   2263     sqlite3Error(db, SQLITE_OK, 0);
  2238   2264     sqlite3RegisterBuiltinFunctions(db);
  2239   2265   
  2240   2266     /* Load automatic extensions - extensions that have been registered
  2241   2267     ** using the sqlite3_automatic_extension() API.
  2242   2268     */
  2243         -  sqlite3AutoLoadExtensions(db);
  2244   2269     rc = sqlite3_errcode(db);
  2245         -  if( rc!=SQLITE_OK ){
  2246         -    goto opendb_out;
         2270  +  if( rc==SQLITE_OK ){
         2271  +    sqlite3AutoLoadExtensions(db);
         2272  +    rc = sqlite3_errcode(db);
         2273  +    if( rc!=SQLITE_OK ){
         2274  +      goto opendb_out;
         2275  +    }
  2247   2276     }
  2248   2277   
  2249   2278   #ifdef SQLITE_ENABLE_FTS1
  2250   2279     if( !db->mallocFailed ){
  2251   2280       extern int sqlite3Fts1Init(sqlite3*);
  2252   2281       rc = sqlite3Fts1Init(db);
  2253   2282     }
................................................................................
  2380   2409     int enc, 
  2381   2410     void* pCtx,
  2382   2411     int(*xCompare)(void*,int,const void*,int,const void*)
  2383   2412   ){
  2384   2413     int rc;
  2385   2414     sqlite3_mutex_enter(db->mutex);
  2386   2415     assert( !db->mallocFailed );
  2387         -  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
         2416  +  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  2388   2417     rc = sqlite3ApiExit(db, rc);
  2389   2418     sqlite3_mutex_leave(db->mutex);
  2390   2419     return rc;
  2391   2420   }
  2392   2421   
  2393   2422   /*
  2394   2423   ** Register a new collation sequence with the database handle db.
................................................................................
  2400   2429     void* pCtx,
  2401   2430     int(*xCompare)(void*,int,const void*,int,const void*),
  2402   2431     void(*xDel)(void*)
  2403   2432   ){
  2404   2433     int rc;
  2405   2434     sqlite3_mutex_enter(db->mutex);
  2406   2435     assert( !db->mallocFailed );
  2407         -  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
         2436  +  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  2408   2437     rc = sqlite3ApiExit(db, rc);
  2409   2438     sqlite3_mutex_leave(db->mutex);
  2410   2439     return rc;
  2411   2440   }
  2412   2441   
  2413   2442   #ifndef SQLITE_OMIT_UTF16
  2414   2443   /*
................................................................................
  2423   2452   ){
  2424   2453     int rc = SQLITE_OK;
  2425   2454     char *zName8;
  2426   2455     sqlite3_mutex_enter(db->mutex);
  2427   2456     assert( !db->mallocFailed );
  2428   2457     zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  2429   2458     if( zName8 ){
  2430         -    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
         2459  +    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  2431   2460       sqlite3DbFree(db, zName8);
  2432   2461     }
  2433   2462     rc = sqlite3ApiExit(db, rc);
  2434   2463     sqlite3_mutex_leave(db->mutex);
  2435   2464     return rc;
  2436   2465   }
  2437   2466   #endif /* SQLITE_OMIT_UTF16 */
................................................................................
  2906   2935         const char *zWord = va_arg(ap, const char*);
  2907   2936         int n = sqlite3Strlen30(zWord);
  2908   2937         rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  2909   2938         break;
  2910   2939       }
  2911   2940   #endif 
  2912   2941   
  2913         -    /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
  2914         -    **
  2915         -    ** Return the size of a pcache header in bytes.
  2916         -    */
  2917         -    case SQLITE_TESTCTRL_PGHDRSZ: {
  2918         -      rc = sizeof(PgHdr);
  2919         -      break;
  2920         -    }
  2921         -
  2922   2942       /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  2923   2943       **
  2924   2944       ** Pass pFree into sqlite3ScratchFree(). 
  2925   2945       ** If sz>0 then allocate a scratch buffer into pNew.  
  2926   2946       */
  2927   2947       case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  2928   2948         void *pFree, **ppNew;
................................................................................
  2942   2962       ** undo this setting.
  2943   2963       */
  2944   2964       case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  2945   2965         sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  2946   2966         break;
  2947   2967       }
  2948   2968   
         2969  +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
         2970  +    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
         2971  +    **                        sqlite3_stmt*,const char**);
         2972  +    **
         2973  +    ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
         2974  +    ** a string that describes the optimized parse tree.  This test-control
         2975  +    ** returns a pointer to that string.
         2976  +    */
         2977  +    case SQLITE_TESTCTRL_EXPLAIN_STMT: {
         2978  +      sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
         2979  +      const char **pzRet = va_arg(ap, const char**);
         2980  +      *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
         2981  +      break;
         2982  +    }
         2983  +#endif
         2984  +
  2949   2985     }
  2950   2986     va_end(ap);
  2951   2987   #endif /* SQLITE_OMIT_BUILTIN_TEST */
  2952   2988     return rc;
  2953   2989   }
  2954   2990   
  2955   2991   /*
................................................................................
  2960   2996   ** The zFilename argument is the filename pointer passed into the xOpen()
  2961   2997   ** method of a VFS implementation.  The zParam argument is the name of the
  2962   2998   ** query parameter we seek.  This routine returns the value of the zParam
  2963   2999   ** parameter if it exists.  If the parameter does not exist, this routine
  2964   3000   ** returns a NULL pointer.
  2965   3001   */
  2966   3002   const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
         3003  +  if( zFilename==0 ) return 0;
  2967   3004     zFilename += sqlite3Strlen30(zFilename) + 1;
  2968   3005     while( zFilename[0] ){
  2969   3006       int x = strcmp(zFilename, zParam);
  2970   3007       zFilename += sqlite3Strlen30(zFilename) + 1;
  2971   3008       if( x==0 ) return zFilename;
  2972   3009       zFilename += sqlite3Strlen30(zFilename) + 1;
         3010  +  }
         3011  +  return 0;
         3012  +}
         3013  +
         3014  +/*
         3015  +** Return a boolean value for a query parameter.
         3016  +*/
         3017  +int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
         3018  +  const char *z = sqlite3_uri_parameter(zFilename, zParam);
         3019  +  return z ? sqlite3GetBoolean(z) : (bDflt!=0);
         3020  +}
         3021  +
         3022  +/*
         3023  +** Return a 64-bit integer value for a query parameter.
         3024  +*/
         3025  +sqlite3_int64 sqlite3_uri_int64(
         3026  +  const char *zFilename,    /* Filename as passed to xOpen */
         3027  +  const char *zParam,       /* URI parameter sought */
         3028  +  sqlite3_int64 bDflt       /* return if parameter is missing */
         3029  +){
         3030  +  const char *z = sqlite3_uri_parameter(zFilename, zParam);
         3031  +  sqlite3_int64 v;
         3032  +  if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
         3033  +    bDflt = v;
         3034  +  }
         3035  +  return bDflt;
         3036  +}
         3037  +
         3038  +/*
         3039  +** Return the filename of the database associated with a database
         3040  +** connection.
         3041  +*/
         3042  +const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
         3043  +  int i;
         3044  +  for(i=0; i<db->nDb; i++){
         3045  +    if( db->aDb[i].pBt && sqlite3StrICmp(zDbName, db->aDb[i].zName)==0 ){
         3046  +      return sqlite3BtreeGetFilename(db->aDb[i].pBt);
         3047  +    }
  2973   3048     }
  2974   3049     return 0;
  2975   3050   }

Changes to src/malloc.c.

   126    126   ** Set the soft heap-size limit for the library. Passing a zero or 
   127    127   ** negative value indicates no limit.
   128    128   */
   129    129   sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
   130    130     sqlite3_int64 priorLimit;
   131    131     sqlite3_int64 excess;
   132    132   #ifndef SQLITE_OMIT_AUTOINIT
   133         -  sqlite3_initialize();
          133  +  int rc = sqlite3_initialize();
          134  +  if( rc ) return -1;
   134    135   #endif
   135    136     sqlite3_mutex_enter(mem0.mutex);
   136    137     priorLimit = mem0.alarmThreshold;
   137    138     sqlite3_mutex_leave(mem0.mutex);
   138    139     if( n<0 ) return priorLimit;
   139    140     if( n>0 ){
   140    141       sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);

Changes to src/mem1.c.

    22     22   /*
    23     23   ** This version of the memory allocator is the default.  It is
    24     24   ** used when no other memory allocator is specified using compile-time
    25     25   ** macros.
    26     26   */
    27     27   #ifdef SQLITE_SYSTEM_MALLOC
    28     28   
           29  +/*
           30  +** Windows systems have malloc_usable_size() but it is called _msize()
           31  +*/
           32  +#if !defined(HAVE_MALLOC_USABLE_SIZE) && SQLITE_OS_WIN
           33  +# define HAVE_MALLOC_USABLE_SIZE 1
           34  +# define malloc_usable_size _msize
           35  +#endif
           36  +
           37  +#if defined(__APPLE__)
           38  +
           39  +/*
           40  +** Use the zone allocator available on apple products
           41  +*/
           42  +#include <sys/sysctl.h>
           43  +#include <malloc/malloc.h>
           44  +#include <libkern/OSAtomic.h>
           45  +static malloc_zone_t* _sqliteZone_;
           46  +#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
           47  +#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
           48  +#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
           49  +#define SQLITE_MALLOCSIZE(x) \
           50  +        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
           51  +
           52  +#else /* if not __APPLE__ */
           53  +
           54  +/*
           55  +** Use standard C library malloc and free on non-Apple systems.
           56  +*/
           57  +#define SQLITE_MALLOC(x)    malloc(x)
           58  +#define SQLITE_FREE(x)      free(x)
           59  +#define SQLITE_REALLOC(x,y) realloc((x),(y))
           60  +
           61  +#ifdef HAVE_MALLOC_USABLE_SIZE
           62  +#include <malloc.h>
           63  +#define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
           64  +#else
           65  +#undef SQLITE_MALLOCSIZE
           66  +#endif
           67  +
           68  +#endif /* __APPLE__ or not __APPLE__ */
           69  +
    29     70   /*
    30     71   ** Like malloc(), but remember the size of the allocation
    31     72   ** so that we can find it later using sqlite3MemSize().
    32     73   **
    33     74   ** For this low-level routine, we are guaranteed that nByte>0 because
    34     75   ** cases of nByte<=0 will be intercepted and dealt with by higher level
    35     76   ** routines.
    36     77   */
    37     78   static void *sqlite3MemMalloc(int nByte){
           79  +#ifdef SQLITE_MALLOCSIZE
           80  +  void *p = SQLITE_MALLOC( nByte );
           81  +  if( p==0 ){
           82  +    testcase( sqlite3GlobalConfig.xLog!=0 );
           83  +    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
           84  +  }
           85  +  return p;
           86  +#else
    38     87     sqlite3_int64 *p;
    39     88     assert( nByte>0 );
    40     89     nByte = ROUND8(nByte);
    41         -  p = malloc( nByte+8 );
           90  +  p = SQLITE_MALLOC( nByte+8 );
    42     91     if( p ){
    43     92       p[0] = nByte;
    44     93       p++;
    45     94     }else{
    46     95       testcase( sqlite3GlobalConfig.xLog!=0 );
    47     96       sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
    48     97     }
    49     98     return (void *)p;
           99  +#endif
    50    100   }
    51    101   
    52    102   /*
    53    103   ** Like free() but works for allocations obtained from sqlite3MemMalloc()
    54    104   ** or sqlite3MemRealloc().
    55    105   **
    56    106   ** For this low-level routine, we already know that pPrior!=0 since
    57    107   ** cases where pPrior==0 will have been intecepted and dealt with
    58    108   ** by higher-level routines.
    59    109   */
    60    110   static void sqlite3MemFree(void *pPrior){
          111  +#ifdef SQLITE_MALLOCSIZE
          112  +  SQLITE_FREE(pPrior);
          113  +#else
    61    114     sqlite3_int64 *p = (sqlite3_int64*)pPrior;
    62    115     assert( pPrior!=0 );
    63    116     p--;
    64         -  free(p);
          117  +  SQLITE_FREE(p);
          118  +#endif
    65    119   }
    66    120   
    67    121   /*
    68    122   ** Report the allocated size of a prior return from xMalloc()
    69    123   ** or xRealloc().
    70    124   */
    71    125   static int sqlite3MemSize(void *pPrior){
          126  +#ifdef SQLITE_MALLOCSIZE
          127  +  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
          128  +#else
    72    129     sqlite3_int64 *p;
    73    130     if( pPrior==0 ) return 0;
    74    131     p = (sqlite3_int64*)pPrior;
    75    132     p--;
    76    133     return (int)p[0];
          134  +#endif
    77    135   }
    78    136   
    79    137   /*
    80    138   ** Like realloc().  Resize an allocation previously obtained from
    81    139   ** sqlite3MemMalloc().
    82    140   **
    83    141   ** For this low-level interface, we know that pPrior!=0.  Cases where
    84    142   ** pPrior==0 while have been intercepted by higher-level routine and
    85    143   ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
    86    144   ** cases where nByte<=0 will have been intercepted by higher-level
    87    145   ** routines and redirected to xFree.
    88    146   */
    89    147   static void *sqlite3MemRealloc(void *pPrior, int nByte){
          148  +#ifdef SQLITE_MALLOCSIZE
          149  +  void *p = SQLITE_REALLOC(pPrior, nByte);
          150  +  if( p==0 ){
          151  +    testcase( sqlite3GlobalConfig.xLog!=0 );
          152  +    sqlite3_log(SQLITE_NOMEM,
          153  +      "failed memory resize %u to %u bytes",
          154  +      SQLITE_MALLOCSIZE(pPrior), nByte);
          155  +  }
          156  +  return p;
          157  +#else
    90    158     sqlite3_int64 *p = (sqlite3_int64*)pPrior;
    91    159     assert( pPrior!=0 && nByte>0 );
    92    160     assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
    93    161     p--;
    94         -  p = realloc(p, nByte+8 );
          162  +  p = SQLITE_REALLOC(p, nByte+8 );
    95    163     if( p ){
    96    164       p[0] = nByte;
    97    165       p++;
    98    166     }else{
    99    167       testcase( sqlite3GlobalConfig.xLog!=0 );
   100    168       sqlite3_log(SQLITE_NOMEM,
   101    169         "failed memory resize %u to %u bytes",
   102    170         sqlite3MemSize(pPrior), nByte);
   103    171     }
   104    172     return (void*)p;
          173  +#endif
   105    174   }
   106    175   
   107    176   /*
   108    177   ** Round up a request size to the next valid allocation size.
   109    178   */
   110    179   static int sqlite3MemRoundup(int n){
   111    180     return ROUND8(n);
   112    181   }
   113    182   
   114    183   /*
   115    184   ** Initialize this module.
   116    185   */
   117    186   static int sqlite3MemInit(void *NotUsed){
          187  +#if defined(__APPLE__)
          188  +  int cpuCount;
          189  +  size_t len;
          190  +  if( _sqliteZone_ ){
          191  +    return SQLITE_OK;
          192  +  }
          193  +  len = sizeof(cpuCount);
          194  +  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
          195  +  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
          196  +  if( cpuCount>1 ){
          197  +    /* defer MT decisions to system malloc */
          198  +    _sqliteZone_ = malloc_default_zone();
          199  +  }else{
          200  +    /* only 1 core, use our own zone to contention over global locks, 
          201  +    ** e.g. we have our own dedicated locks */
          202  +    bool success;		
          203  +    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
          204  +    malloc_set_zone_name(newzone, "Sqlite_Heap");
          205  +    do{
          206  +      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
          207  +                                 (void * volatile *)&_sqliteZone_);
          208  +    }while(!_sqliteZone_);
          209  +    if( !success ){	
          210  +      /* somebody registered a zone first */
          211  +      malloc_destroy_zone(newzone);
          212  +    }
          213  +  }
          214  +#endif
   118    215     UNUSED_PARAMETER(NotUsed);
   119    216     return SQLITE_OK;
   120    217   }
   121    218   
   122    219   /*
   123    220   ** Deinitialize this module.
   124    221   */

Changes to src/mutex.c.

   146    146     return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
   147    147   }
   148    148   int sqlite3_mutex_notheld(sqlite3_mutex *p){
   149    149     return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
   150    150   }
   151    151   #endif
   152    152   
   153         -#endif /* SQLITE_MUTEX_OMIT */
          153  +#endif /* !defined(SQLITE_MUTEX_OMIT) */

Changes to src/mutex_noop.c.

   198    198   ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
   199    199   ** is used regardless of the run-time threadsafety setting.
   200    200   */
   201    201   #ifdef SQLITE_MUTEX_NOOP
   202    202   sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
   203    203     return sqlite3NoopMutex();
   204    204   }
   205         -#endif /* SQLITE_MUTEX_NOOP */
   206         -#endif /* SQLITE_MUTEX_OMIT */
          205  +#endif /* defined(SQLITE_MUTEX_NOOP) */
          206  +#endif /* !defined(SQLITE_MUTEX_OMIT) */

Changes to src/mutex_unix.c.

   344    344       0
   345    345   #endif
   346    346     };
   347    347   
   348    348     return &sMutex;
   349    349   }
   350    350   
   351         -#endif /* SQLITE_MUTEX_PTHREAD */
          351  +#endif /* SQLITE_MUTEX_PTHREADS */

Changes to src/os.c.

    23     23   ** from within OsOpen()), but some third-party implementations may.
    24     24   ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
    25     25   ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
    26     26   **
    27     27   ** The following functions are instrumented for malloc() failure 
    28     28   ** testing:
    29     29   **
    30         -**     sqlite3OsOpen()
    31     30   **     sqlite3OsRead()
    32     31   **     sqlite3OsWrite()
    33     32   **     sqlite3OsSync()
           33  +**     sqlite3OsFileSize()
    34     34   **     sqlite3OsLock()
           35  +**     sqlite3OsCheckReservedLock()
           36  +**     sqlite3OsFileControl()
           37  +**     sqlite3OsShmMap()
           38  +**     sqlite3OsOpen()
           39  +**     sqlite3OsDelete()
           40  +**     sqlite3OsAccess()
           41  +**     sqlite3OsFullPathname()
    35     42   **
    36     43   */
    37     44   #if defined(SQLITE_TEST)
    38     45   int sqlite3_memdebug_vfs_oom_test = 1;
    39     46     #define DO_OS_MALLOC_TEST(x)                                       \
    40     47     if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
    41     48       void *pTstAlloc = sqlite3Malloc(10);                             \
................................................................................
    87     94     return id->pMethods->xUnlock(id, lockType);
    88     95   }
    89     96   int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
    90     97     DO_OS_MALLOC_TEST(id);
    91     98     return id->pMethods->xCheckReservedLock(id, pResOut);
    92     99   }
    93    100   int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
          101  +  DO_OS_MALLOC_TEST(id);
    94    102     return id->pMethods->xFileControl(id, op, pArg);
    95    103   }
    96    104   int sqlite3OsSectorSize(sqlite3_file *id){
    97    105     int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
    98    106     return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
    99    107   }
   100    108   int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
................................................................................
   112    120   int sqlite3OsShmMap(
   113    121     sqlite3_file *id,               /* Database file handle */
   114    122     int iPage,
   115    123     int pgsz,
   116    124     int bExtend,                    /* True to extend file if necessary */
   117    125     void volatile **pp              /* OUT: Pointer to mapping */
   118    126   ){
          127  +  DO_OS_MALLOC_TEST(id);
   119    128     return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
   120    129   }
   121    130   
   122    131   /*
   123    132   ** The next group of routines are convenience wrappers around the
   124    133   ** VFS methods.
   125    134   */
................................................................................
   128    137     const char *zPath, 
   129    138     sqlite3_file *pFile, 
   130    139     int flags, 
   131    140     int *pFlagsOut
   132    141   ){
   133    142     int rc;
   134    143     DO_OS_MALLOC_TEST(0);
   135         -  /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
          144  +  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
   136    145     ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
   137    146     ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
   138    147     ** reaching the VFS. */
   139    148     rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
   140    149     assert( rc==SQLITE_OK || pFile->pMethods==0 );
   141    150     return rc;
   142    151   }
   143    152   int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
          153  +  DO_OS_MALLOC_TEST(0);
   144    154     return pVfs->xDelete(pVfs, zPath, dirSync);
   145    155   }
   146    156   int sqlite3OsAccess(
   147    157     sqlite3_vfs *pVfs, 
   148    158     const char *zPath, 
   149    159     int flags, 
   150    160     int *pResOut
................................................................................
   154    164   }
   155    165   int sqlite3OsFullPathname(
   156    166     sqlite3_vfs *pVfs, 
   157    167     const char *zPath, 
   158    168     int nPathOut, 
   159    169     char *zPathOut
   160    170   ){
          171  +  DO_OS_MALLOC_TEST(0);
   161    172     zPathOut[0] = 0;
   162    173     return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
   163    174   }
   164    175   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   165    176   void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
   166    177     return pVfs->xDlOpen(pVfs, zPath);
   167    178   }

Changes to src/os.h.

    60     60   #  define SQLITE_OS_OS2 0
    61     61   # endif
    62     62   #else
    63     63   # ifndef SQLITE_OS_WIN
    64     64   #  define SQLITE_OS_WIN 0
    65     65   # endif
    66     66   #endif
    67         -
    68         -/*
    69         -** Determine if we are dealing with WindowsCE - which has a much
    70         -** reduced API.
    71         -*/
    72         -#if defined(_WIN32_WCE)
    73         -# define SQLITE_OS_WINCE 1
    74         -#else
    75         -# define SQLITE_OS_WINCE 0
    76         -#endif
    77         -
    78     67   
    79     68   /*
    80     69   ** Define the maximum size of a temporary filename
    81     70   */
    82     71   #if SQLITE_OS_WIN
    83     72   # include <windows.h>
    84     73   # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
................................................................................
    96     85   # include <os2.h>
    97     86   # include <uconv.h>
    98     87   # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
    99     88   #else
   100     89   # define SQLITE_TEMPNAME_SIZE 200
   101     90   #endif
   102     91   
           92  +/*
           93  +** Determine if we are dealing with Windows NT.
           94  +*/
           95  +#if defined(_WIN32_WINNT)
           96  +# define SQLITE_OS_WINNT 1
           97  +#else
           98  +# define SQLITE_OS_WINNT 0
           99  +#endif
          100  +
          101  +/*
          102  +** Determine if we are dealing with WindowsCE - which has a much
          103  +** reduced API.
          104  +*/
          105  +#if defined(_WIN32_WCE)
          106  +# define SQLITE_OS_WINCE 1
          107  +#else
          108  +# define SQLITE_OS_WINCE 0
          109  +#endif
          110  +
   103    111   /* If the SET_FULLSYNC macro is not defined above, then make it
   104    112   ** a no-op
   105    113   */
   106    114   #ifndef SET_FULLSYNC
   107    115   # define SET_FULLSYNC(x,y)
   108    116   #endif
   109    117   
   110    118   /*
   111    119   ** The default size of a disk sector
   112    120   */
   113    121   #ifndef SQLITE_DEFAULT_SECTOR_SIZE
   114         -# define SQLITE_DEFAULT_SECTOR_SIZE 512
          122  +# define SQLITE_DEFAULT_SECTOR_SIZE 4096
   115    123   #endif
   116    124   
   117    125   /*
   118    126   ** Temporary files are named starting with this prefix followed by 16 random
   119    127   ** alphanumeric characters, and no file extension. They are stored in the
   120    128   ** OS's standard temporary file directory, and are deleted prior to exit.
   121    129   ** If sqlite is being embedded in another program, you may wish to change the

Changes to src/os_unix.c.

   118    118   #include <unistd.h>
   119    119   #include <time.h>
   120    120   #include <sys/time.h>
   121    121   #include <errno.h>
   122    122   #ifndef SQLITE_OMIT_WAL
   123    123   #include <sys/mman.h>
   124    124   #endif
          125  +
   125    126   
   126    127   #if SQLITE_ENABLE_LOCKING_STYLE
   127    128   # include <sys/ioctl.h>
   128    129   # if OS_VXWORKS
   129    130   #  include <semaphore.h>
   130    131   #  include <limits.h>
   131    132   # else
................................................................................
   202    203   /*
   203    204   ** The unixFile structure is subclass of sqlite3_file specific to the unix
   204    205   ** VFS implementations.
   205    206   */
   206    207   typedef struct unixFile unixFile;
   207    208   struct unixFile {
   208    209     sqlite3_io_methods const *pMethod;  /* Always the first entry */
          210  +  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
   209    211     unixInodeInfo *pInode;              /* Info about locks on this inode */
   210    212     int h;                              /* The file descriptor */
   211    213     unsigned char eFileLock;            /* The type of lock held on this fd */
   212    214     unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
   213    215     int lastErrno;                      /* The unix errno from last I/O error */
   214    216     void *lockingContext;               /* Locking style specific state */
   215    217     UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
................................................................................
   253    255   #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
   254    256   #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
   255    257   #ifndef SQLITE_DISABLE_DIRSYNC
   256    258   # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
   257    259   #else
   258    260   # define UNIXFILE_DIRSYNC    0x00
   259    261   #endif
          262  +#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
   260    263   
   261    264   /*
   262    265   ** Include code that is common to all os_*.c files
   263    266   */
   264    267   #include "os_common.h"
   265    268   
   266    269   /*
................................................................................
   403    406   
   404    407     { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
   405    408   #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
   406    409   
   407    410     { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
   408    411   #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
   409    412   
          413  +  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
          414  +#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
          415  +
          416  +  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
          417  +#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
          418  +
   410    419   }; /* End of the overrideable system calls */
   411    420   
   412    421   /*
   413    422   ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
   414    423   ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
   415    424   ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
   416    425   ** system call named zName.
................................................................................
  1841   1850   /******************* End of the no-op lock implementation *********************
  1842   1851   ******************************************************************************/
  1843   1852   
  1844   1853   /******************************************************************************
  1845   1854   ************************* Begin dot-file Locking ******************************
  1846   1855   **
  1847   1856   ** The dotfile locking implementation uses the existance of separate lock
  1848         -** files in order to control access to the database.  This works on just
  1849         -** about every filesystem imaginable.  But there are serious downsides:
         1857  +** files (really a directory) to control access to the database.  This works
         1858  +** on just about every filesystem imaginable.  But there are serious downsides:
  1850   1859   **
  1851   1860   **    (1)  There is zero concurrency.  A single reader blocks all other
  1852   1861   **         connections from reading or writing the database.
  1853   1862   **
  1854   1863   **    (2)  An application crash or power loss can leave stale lock files
  1855   1864   **         sitting around that need to be cleared manually.
  1856   1865   **
  1857   1866   ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  1858   1867   ** other locking strategy is available.
  1859   1868   **
  1860         -** Dotfile locking works by creating a file in the same directory as the
  1861         -** database and with the same name but with a ".lock" extension added.
  1862         -** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
  1863         -** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
         1869  +** Dotfile locking works by creating a subdirectory in the same directory as
         1870  +** the database and with the same name but with a ".lock" extension added.
         1871  +** The existance of a lock directory implies an EXCLUSIVE lock.  All other
         1872  +** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  1864   1873   */
  1865   1874   
  1866   1875   /*
  1867   1876   ** The file suffix added to the data base filename in order to create the
  1868         -** lock file.
         1877  +** lock directory.
  1869   1878   */
  1870   1879   #define DOTLOCK_SUFFIX ".lock"
  1871   1880   
  1872   1881   /*
  1873   1882   ** This routine checks if there is a RESERVED lock held on the specified
  1874   1883   ** file by this or any other process. If such a lock is held, set *pResOut
  1875   1884   ** to a non-zero value otherwise *pResOut is set to zero.  The return value
................................................................................
  1928   1937   ** routine to lower a locking level.
  1929   1938   **
  1930   1939   ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  1931   1940   ** But we track the other locking levels internally.
  1932   1941   */
  1933   1942   static int dotlockLock(sqlite3_file *id, int eFileLock) {
  1934   1943     unixFile *pFile = (unixFile*)id;
  1935         -  int fd;
  1936   1944     char *zLockFile = (char *)pFile->lockingContext;
  1937   1945     int rc = SQLITE_OK;
  1938   1946   
  1939   1947   
  1940   1948     /* If we have any lock, then the lock file already exists.  All we have
  1941   1949     ** to do is adjust our internal record of the lock level.
  1942   1950     */
................................................................................
  1948   1956   #else
  1949   1957       utimes(zLockFile, NULL);
  1950   1958   #endif
  1951   1959       return SQLITE_OK;
  1952   1960     }
  1953   1961     
  1954   1962     /* grab an exclusive lock */
  1955         -  fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
  1956         -  if( fd<0 ){
  1957         -    /* failed to open/create the file, someone else may have stolen the lock */
         1963  +  rc = osMkdir(zLockFile, 0777);
         1964  +  if( rc<0 ){
         1965  +    /* failed to open/create the lock directory */
  1958   1966       int tErrno = errno;
  1959   1967       if( EEXIST == tErrno ){
  1960   1968         rc = SQLITE_BUSY;
  1961   1969       } else {
  1962   1970         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  1963   1971         if( IS_LOCK_ERROR(rc) ){
  1964   1972           pFile->lastErrno = tErrno;
  1965   1973         }
  1966   1974       }
  1967   1975       return rc;
  1968   1976     } 
  1969         -  robust_close(pFile, fd, __LINE__);
  1970   1977     
  1971   1978     /* got it, set the type and return ok */
  1972   1979     pFile->eFileLock = eFileLock;
  1973   1980     return rc;
  1974   1981   }
  1975   1982   
  1976   1983   /*
................................................................................
  1981   1988   ** the requested locking level, this routine is a no-op.
  1982   1989   **
  1983   1990   ** When the locking level reaches NO_LOCK, delete the lock file.
  1984   1991   */
  1985   1992   static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  1986   1993     unixFile *pFile = (unixFile*)id;
  1987   1994     char *zLockFile = (char *)pFile->lockingContext;
         1995  +  int rc;
  1988   1996   
  1989   1997     assert( pFile );
  1990   1998     OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  1991   1999   	   pFile->eFileLock, getpid()));
  1992   2000     assert( eFileLock<=SHARED_LOCK );
  1993   2001     
  1994   2002     /* no-op if possible */
................................................................................
  2002   2010     if( eFileLock==SHARED_LOCK ){
  2003   2011       pFile->eFileLock = SHARED_LOCK;
  2004   2012       return SQLITE_OK;
  2005   2013     }
  2006   2014     
  2007   2015     /* To fully unlock the database, delete the lock file */
  2008   2016     assert( eFileLock==NO_LOCK );
  2009         -  if( osUnlink(zLockFile) ){
  2010         -    int rc = 0;
         2017  +  rc = osRmdir(zLockFile);
         2018  +  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
         2019  +  if( rc<0 ){
  2011   2020       int tErrno = errno;
         2021  +    rc = 0;
  2012   2022       if( ENOENT != tErrno ){
  2013   2023         rc = SQLITE_IOERR_UNLOCK;
  2014   2024       }
  2015   2025       if( IS_LOCK_ERROR(rc) ){
  2016   2026         pFile->lastErrno = tErrno;
  2017   2027       }
  2018   2028       return rc; 
................................................................................
  2940   2950   ** See tickets #2741 and #2681.
  2941   2951   **
  2942   2952   ** To avoid stomping the errno value on a failed read the lastErrno value
  2943   2953   ** is set before returning.
  2944   2954   */
  2945   2955   static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  2946   2956     int got;
         2957  +  int prior = 0;
  2947   2958   #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  2948   2959     i64 newOffset;
  2949   2960   #endif
  2950   2961     TIMER_START;
         2962  +  do{
  2951   2963   #if defined(USE_PREAD)
  2952         -  do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
  2953         -  SimulateIOError( got = -1 );
         2964  +    got = osPread(id->h, pBuf, cnt, offset);
         2965  +    SimulateIOError( got = -1 );
  2954   2966   #elif defined(USE_PREAD64)
  2955         -  do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
  2956         -  SimulateIOError( got = -1 );
         2967  +    got = osPread64(id->h, pBuf, cnt, offset);
         2968  +    SimulateIOError( got = -1 );
  2957   2969   #else
  2958         -  newOffset = lseek(id->h, offset, SEEK_SET);
  2959         -  SimulateIOError( newOffset-- );
  2960         -  if( newOffset!=offset ){
  2961         -    if( newOffset == -1 ){
         2970  +    newOffset = lseek(id->h, offset, SEEK_SET);
         2971  +    SimulateIOError( newOffset-- );
         2972  +    if( newOffset!=offset ){
         2973  +      if( newOffset == -1 ){
         2974  +        ((unixFile*)id)->lastErrno = errno;
         2975  +      }else{
         2976  +        ((unixFile*)id)->lastErrno = 0;			
         2977  +      }
         2978  +      return -1;
         2979  +    }
         2980  +    got = osRead(id->h, pBuf, cnt);
         2981  +#endif
         2982  +    if( got==cnt ) break;
         2983  +    if( got<0 ){
         2984  +      if( errno==EINTR ){ got = 1; continue; }
         2985  +      prior = 0;
  2962   2986         ((unixFile*)id)->lastErrno = errno;
  2963         -    }else{
  2964         -      ((unixFile*)id)->lastErrno = 0;			
         2987  +      break;
         2988  +    }else if( got>0 ){
         2989  +      cnt -= got;
         2990  +      offset += got;
         2991  +      prior += got;
         2992  +      pBuf = (void*)(got + (char*)pBuf);
  2965   2993       }
  2966         -    return -1;
  2967         -  }
  2968         -  do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
  2969         -#endif
         2994  +  }while( got>0 );
  2970   2995     TIMER_END;
  2971         -  if( got<0 ){
  2972         -    ((unixFile*)id)->lastErrno = errno;
  2973         -  }
  2974         -  OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
  2975         -  return got;
         2996  +  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
         2997  +            id->h, got+prior, offset-prior, TIMER_ELAPSED));
         2998  +  return got+prior;
  2976   2999   }
  2977   3000   
  2978   3001   /*
  2979   3002   ** Read data from a file into a buffer.  Return SQLITE_OK if all
  2980   3003   ** bytes were read successfully and SQLITE_IOERR if anything goes
  2981   3004   ** wrong.
  2982   3005   */
................................................................................
  3472   3495         }
  3473   3496   #endif
  3474   3497       }
  3475   3498     }
  3476   3499   
  3477   3500     return SQLITE_OK;
  3478   3501   }
         3502  +
         3503  +/*
         3504  +** If *pArg is inititially negative then this is a query.  Set *pArg to
         3505  +** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
         3506  +**
         3507  +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
         3508  +*/
         3509  +static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
         3510  +  if( *pArg<0 ){
         3511  +    *pArg = (pFile->ctrlFlags & mask)!=0;
         3512  +  }else if( (*pArg)==0 ){
         3513  +    pFile->ctrlFlags &= ~mask;
         3514  +  }else{
         3515  +    pFile->ctrlFlags |= mask;
         3516  +  }
         3517  +}
  3479   3518   
  3480   3519   /*
  3481   3520   ** Information and control of an open file handle.
  3482   3521   */
  3483   3522   static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  3484   3523     unixFile *pFile = (unixFile*)id;
  3485   3524     switch( op ){
................................................................................
  3499   3538         int rc;
  3500   3539         SimulateIOErrorBenign(1);
  3501   3540         rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  3502   3541         SimulateIOErrorBenign(0);
  3503   3542         return rc;
  3504   3543       }
  3505   3544       case SQLITE_FCNTL_PERSIST_WAL: {
  3506         -      int bPersist = *(int*)pArg;
  3507         -      if( bPersist<0 ){
  3508         -        *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
  3509         -      }else if( bPersist==0 ){
  3510         -        pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
  3511         -      }else{
  3512         -        pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
  3513         -      }
         3545  +      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
         3546  +      return SQLITE_OK;
         3547  +    }
         3548  +    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
         3549  +      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
         3550  +      return SQLITE_OK;
         3551  +    }
         3552  +    case SQLITE_FCNTL_VFSNAME: {
         3553  +      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  3514   3554         return SQLITE_OK;
  3515   3555       }
  3516   3556   #ifndef NDEBUG
  3517   3557       /* The pager calls this method to signal that it has done
  3518   3558       ** a rollback and that the database is therefore unchanged and
  3519   3559       ** it hence it is OK for the transaction change counter to be
  3520   3560       ** unchanged.
................................................................................
  3526   3566   #endif
  3527   3567   #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  3528   3568       case SQLITE_SET_LOCKPROXYFILE:
  3529   3569       case SQLITE_GET_LOCKPROXYFILE: {
  3530   3570         return proxyFileControl(id,op,pArg);
  3531   3571       }
  3532   3572   #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  3533         -    case SQLITE_FCNTL_SYNC_OMITTED: {
  3534         -      return SQLITE_OK;  /* A no-op */
  3535         -    }
  3536   3573     }
  3537   3574     return SQLITE_NOTFOUND;
  3538   3575   }
  3539   3576   
  3540   3577   /*
  3541   3578   ** Return the sector size in bytes of the underlying block device for
  3542   3579   ** the specified file. This is almost always 512 bytes, but may be
................................................................................
  3543   3580   ** larger for some devices.
  3544   3581   **
  3545   3582   ** SQLite code assumes this function cannot fail. It also assumes that
  3546   3583   ** if two files are created in the same file-system directory (i.e.
  3547   3584   ** a database and its journal file) that the sector size will be the
  3548   3585   ** same for both.
  3549   3586   */
  3550         -static int unixSectorSize(sqlite3_file *NotUsed){
  3551         -  UNUSED_PARAMETER(NotUsed);
         3587  +static int unixSectorSize(sqlite3_file *pFile){
         3588  +  (void)pFile;
  3552   3589     return SQLITE_DEFAULT_SECTOR_SIZE;
  3553   3590   }
  3554   3591   
  3555   3592   /*
  3556         -** Return the device characteristics for the file. This is always 0 for unix.
         3593  +** Return the device characteristics for the file.
         3594  +**
         3595  +** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
         3596  +** However, that choice is contraversial since technically the underlying
         3597  +** file system does not always provide powersafe overwrites.  (In other
         3598  +** words, after a power-loss event, parts of the file that were never
         3599  +** written might end up being altered.)  However, non-PSOW behavior is very,
         3600  +** very rare.  And asserting PSOW makes a large reduction in the amount
         3601  +** of required I/O for journaling, since a lot of padding is eliminated.
         3602  +**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
         3603  +** available to turn it off and URI query parameter available to turn it off.
  3557   3604   */
  3558         -static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
  3559         -  UNUSED_PARAMETER(NotUsed);
  3560         -  return 0;
         3605  +static int unixDeviceCharacteristics(sqlite3_file *id){
         3606  +  unixFile *p = (unixFile*)id;
         3607  +  if( p->ctrlFlags & UNIXFILE_PSOW ){
         3608  +    return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
         3609  +  }else{
         3610  +    return 0;
         3611  +  }
  3561   3612   }
  3562   3613   
  3563   3614   #ifndef SQLITE_OMIT_WAL
  3564   3615   
  3565   3616   
  3566   3617   /*
  3567   3618   ** Object used to represent an shared memory buffer.  
................................................................................
  3808   3859       */
  3809   3860       if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  3810   3861         rc = SQLITE_IOERR_FSTAT;
  3811   3862         goto shm_open_err;
  3812   3863       }
  3813   3864   
  3814   3865   #ifdef SQLITE_SHM_DIRECTORY
  3815         -    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
         3866  +    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  3816   3867   #else
  3817         -    nShmFilename = 5 + (int)strlen(pDbFd->zPath);
         3868  +    nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  3818   3869   #endif
  3819   3870       pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  3820   3871       if( pShmNode==0 ){
  3821   3872         rc = SQLITE_NOMEM;
  3822   3873         goto shm_open_err;
  3823   3874       }
  3824   3875       memset(pShmNode, 0, sizeof(*pShmNode));
................................................................................
  3837   3888       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  3838   3889       if( pShmNode->mutex==0 ){
  3839   3890         rc = SQLITE_NOMEM;
  3840   3891         goto shm_open_err;
  3841   3892       }
  3842   3893   
  3843   3894       if( pInode->bProcessLock==0 ){
  3844         -      const char *zRO;
  3845   3895         int openFlags = O_RDWR | O_CREAT;
  3846         -      zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
  3847         -      if( zRO && sqlite3GetBoolean(zRO) ){
         3896  +      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  3848   3897           openFlags = O_RDONLY;
  3849   3898           pShmNode->isReadonly = 1;
  3850   3899         }
  3851   3900         pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  3852   3901         if( pShmNode->h<0 ){
  3853   3902           if( pShmNode->h<0 ){
  3854   3903             rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
................................................................................
  4536   4585   #endif
  4537   4586   
  4538   4587     /* No locking occurs in temporary files */
  4539   4588     assert( zFilename!=0 || noLock );
  4540   4589   
  4541   4590     OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
  4542   4591     pNew->h = h;
         4592  +  pNew->pVfs = pVfs;
  4543   4593     pNew->zPath = zFilename;
         4594  +  pNew->ctrlFlags = 0;
         4595  +  if( sqlite3_uri_boolean(zFilename, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
         4596  +    pNew->ctrlFlags |= UNIXFILE_PSOW;
         4597  +  }
  4544   4598     if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
  4545         -    pNew->ctrlFlags = UNIXFILE_EXCL;
  4546         -  }else{
  4547         -    pNew->ctrlFlags = 0;
         4599  +    pNew->ctrlFlags |= UNIXFILE_EXCL;
  4548   4600     }
  4549   4601     if( isReadOnly ){
  4550   4602       pNew->ctrlFlags |= UNIXFILE_RDONLY;
  4551   4603     }
  4552   4604     if( syncDir ){
  4553   4605       pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
  4554   4606     }
................................................................................
  4875   4927       **   "<path to db>-walNN"
  4876   4928       **
  4877   4929       ** where NN is a decimal number. The NN naming schemes are 
  4878   4930       ** used by the test_multiplex.c module.
  4879   4931       */
  4880   4932       nDb = sqlite3Strlen30(zPath) - 1; 
  4881   4933   #ifdef SQLITE_ENABLE_8_3_NAMES
  4882         -    while( nDb>0 && !sqlite3Isalnum(zPath[nDb]) ) nDb--;
         4934  +    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  4883   4935       if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  4884   4936   #else
  4885   4937       while( zPath[nDb]!='-' ){
  4886   4938         assert( nDb>0 );
  4887   4939         assert( zPath[nDb]!='\n' );
  4888   4940         nDb--;
  4889   4941       }
................................................................................
  5711   5763     buf[0] = lockPath[0];
  5712   5764     for( i=1; i<len; i++ ){
  5713   5765       if( lockPath[i] == '/' && (i - start > 0) ){
  5714   5766         /* only mkdir if leaf dir != "." or "/" or ".." */
  5715   5767         if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
  5716   5768            || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  5717   5769           buf[i]='\0';
  5718         -        if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
         5770  +        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  5719   5771             int err=errno;
  5720   5772             if( err!=EEXIST ) {
  5721   5773               OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
  5722   5774                        "'%s' proxy lock path=%s pid=%d\n",
  5723   5775                        buf, strerror(err), lockPath, getpid()));
  5724   5776               return err;
  5725   5777             }
................................................................................
  6747   6799       UNIXVFS("unix-proxy",    proxyIoFinder ),
  6748   6800   #endif
  6749   6801     };
  6750   6802     unsigned int i;          /* Loop counter */
  6751   6803   
  6752   6804     /* Double-check that the aSyscall[] array has been constructed
  6753   6805     ** correctly.  See ticket [bb3a86e890c8e96ab] */
  6754         -  assert( ArraySize(aSyscall)==18 );
         6806  +  assert( ArraySize(aSyscall)==20 );
  6755   6807   
  6756   6808     /* Register all VFSes defined in the aVfs[] array */
  6757   6809     for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  6758   6810       sqlite3_vfs_register(&aVfs[i], i==0);
  6759   6811     }
  6760   6812     return SQLITE_OK; 
  6761   6813   }

Changes to src/os_win.c.

     6      6   **
     7      7   **    May you do good and not evil.
     8      8   **    May you find forgiveness for yourself and forgive others.
     9      9   **    May you share freely, never taking more than you give.
    10     10   **
    11     11   ******************************************************************************
    12     12   **
    13         -** This file contains code that is specific to windows.
           13  +** This file contains code that is specific to Windows.
    14     14   */
    15     15   #include "sqliteInt.h"
    16         -#if SQLITE_OS_WIN               /* This file is used for windows only */
    17         -
    18         -
    19         -/*
    20         -** A Note About Memory Allocation:
    21         -**
    22         -** This driver uses malloc()/free() directly rather than going through
    23         -** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
    24         -** are designed for use on embedded systems where memory is scarce and
    25         -** malloc failures happen frequently.  Win32 does not typically run on
    26         -** embedded systems, and when it does the developers normally have bigger
    27         -** problems to worry about than running out of memory.  So there is not
    28         -** a compelling need to use the wrappers.
    29         -**
    30         -** But there is a good reason to not use the wrappers.  If we use the
    31         -** wrappers then we will get simulated malloc() failures within this
    32         -** driver.  And that causes all kinds of problems for our tests.  We
    33         -** could enhance SQLite to deal with simulated malloc failures within
    34         -** the OS driver, but the code to deal with those failure would not
    35         -** be exercised on Linux (which does not need to malloc() in the driver)
    36         -** and so we would have difficulty writing coverage tests for that
    37         -** code.  Better to leave the code out, we think.
    38         -**
    39         -** The point of this discussion is as follows:  When creating a new
    40         -** OS layer for an embedded system, if you use this file as an example,
    41         -** avoid the use of malloc()/free().  Those routines work ok on windows
    42         -** desktops but not so well in embedded systems.
    43         -*/
    44         -
    45         -#include <winbase.h>
           16  +#if SQLITE_OS_WIN               /* This file is used for Windows only */
    46     17   
    47     18   #ifdef __CYGWIN__
    48     19   # include <sys/cygwin.h>
    49     20   #endif
    50     21   
    51         -/*
    52         -** Macros used to determine whether or not to use threads.
    53         -*/
    54         -#if defined(THREADSAFE) && THREADSAFE
    55         -# define SQLITE_W32_THREADS 1
    56         -#endif
    57         -
    58     22   /*
    59     23   ** Include code that is common to all os_*.c files
    60     24   */
    61     25   #include "os_common.h"
    62     26   
    63     27   /*
    64         -** Some microsoft compilers lack this definition.
           28  +** Some Microsoft compilers lack this definition.
    65     29   */
    66     30   #ifndef INVALID_FILE_ATTRIBUTES
    67     31   # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
    68     32   #endif
    69     33   
    70         -/*
    71         -** Determine if we are dealing with WindowsCE - which has a much
    72         -** reduced API.
    73         -*/
    74         -#if SQLITE_OS_WINCE
    75         -# define AreFileApisANSI() 1
    76         -# define FormatMessageW(a,b,c,d,e,f,g) 0
    77         -#endif
    78         -
    79     34   /* Forward references */
    80     35   typedef struct winShm winShm;           /* A connection to shared-memory */
    81     36   typedef struct winShmNode winShmNode;   /* A region of shared-memory */
    82     37   
    83     38   /*
    84     39   ** WinCE lacks native support for file locking so we have to fake it
    85     40   ** with some code of our own.
................................................................................
   100     55   typedef struct winFile winFile;
   101     56   struct winFile {
   102     57     const sqlite3_io_methods *pMethod; /*** Must be first ***/
   103     58     sqlite3_vfs *pVfs;      /* The VFS used to open this file */
   104     59     HANDLE h;               /* Handle for accessing the file */
   105     60     u8 locktype;            /* Type of lock currently held on this file */
   106     61     short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
   107         -  u8 bPersistWal;         /* True to persist WAL files */
           62  +  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
   108     63     DWORD lastErrno;        /* The Windows errno from the last I/O error */
   109         -  DWORD sectorSize;       /* Sector size of the device file is on */
   110     64     winShm *pShm;           /* Instance of shared memory on this file */
   111     65     const char *zPath;      /* Full pathname of this file */
   112     66     int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
   113     67   #if SQLITE_OS_WINCE
   114         -  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
           68  +  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
   115     69     HANDLE hMutex;          /* Mutex used to control access to shared lock */  
   116     70     HANDLE hShared;         /* Shared memory segment used for locking */
   117     71     winceLock local;        /* Locks obtained by this instance of winFile */
   118     72     winceLock *shared;      /* Global shared lock memory for the file  */
   119     73   #endif
   120     74   };
   121     75   
           76  +/*
           77  +** Allowed values for winFile.ctrlFlags
           78  +*/
           79  +#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
           80  +#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
           81  +
   122     82   /*
   123     83    * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
   124     84    * various Win32 API heap functions instead of our own.
   125     85    */
   126     86   #ifdef SQLITE_WIN32_MALLOC
   127     87   /*
   128     88    * The initial size of the Win32-specific heap.  This value may be zero.
................................................................................
   186    146   static int winMemRoundup(int n);
   187    147   static int winMemInit(void *pAppData);
   188    148   static void winMemShutdown(void *pAppData);
   189    149   
   190    150   const sqlite3_mem_methods *sqlite3MemGetWin32(void);
   191    151   #endif /* SQLITE_WIN32_MALLOC */
   192    152   
   193         -/*
   194         -** Forward prototypes.
   195         -*/
   196         -static int getSectorSize(
   197         -    sqlite3_vfs *pVfs,
   198         -    const char *zRelative     /* UTF-8 file name */
   199         -);
   200         -
   201    153   /*
   202    154   ** The following variable is (normally) set once and never changes
   203         -** thereafter.  It records whether the operating system is Win95
          155  +** thereafter.  It records whether the operating system is Win9x
   204    156   ** or WinNT.
   205    157   **
   206    158   ** 0:   Operating system unknown.
   207         -** 1:   Operating system is Win95.
          159  +** 1:   Operating system is Win9x.
   208    160   ** 2:   Operating system is WinNT.
   209    161   **
   210    162   ** In order to facilitate testing on a WinNT system, the test fixture
   211    163   ** can manually set this value to 1 to emulate Win98 behavior.
   212    164   */
   213    165   #ifdef SQLITE_TEST
   214    166   int sqlite3_os_type = 0;
   215    167   #else
   216    168   static int sqlite3_os_type = 0;
   217    169   #endif
          170  +
          171  +/*
          172  +** Many system calls are accessed through pointer-to-functions so that
          173  +** they may be overridden at runtime to facilitate fault injection during
          174  +** testing and sandboxing.  The following array holds the names and pointers
          175  +** to all overrideable system calls.
          176  +*/
          177  +#if !SQLITE_OS_WINCE
          178  +#  define SQLITE_WIN32_HAS_ANSI
          179  +#endif
          180  +
          181  +#if SQLITE_OS_WINCE || SQLITE_OS_WINNT
          182  +#  define SQLITE_WIN32_HAS_WIDE
          183  +#endif
          184  +
          185  +#ifndef SYSCALL
          186  +#  define SYSCALL sqlite3_syscall_ptr
          187  +#endif
          188  +
          189  +#if SQLITE_OS_WINCE
          190  +/*
          191  +** These macros are necessary because Windows CE does not natively support the
          192  +** Win32 APIs LockFile, UnlockFile, and LockFileEx.
          193  + */
          194  +
          195  +#  define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
          196  +#  define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
          197  +#  define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
          198  +
          199  +/*
          200  +** These are the special syscall hacks for Windows CE.  The locking related
          201  +** defines here refer to the macros defined just above.
          202  + */
          203  +
          204  +#  define osAreFileApisANSI()       1
          205  +#  define osLockFile                LockFile
          206  +#  define osUnlockFile              UnlockFile
          207  +#  define osLockFileEx              LockFileEx
          208  +#endif
          209  +
          210  +static struct win_syscall {
          211  +  const char *zName;            /* Name of the sytem call */
          212  +  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
          213  +  sqlite3_syscall_ptr pDefault; /* Default value */
          214  +} aSyscall[] = {
          215  +#if !SQLITE_OS_WINCE
          216  +  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
          217  +
          218  +#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
          219  +#else
          220  +  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
          221  +#endif
          222  +
          223  +#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
          224  +  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
          225  +#else
          226  +  { "CharLowerW",              (SYSCALL)0,                       0 },
          227  +#endif
          228  +
          229  +#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
          230  +
          231  +#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
          232  +  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
          233  +#else
          234  +  { "CharUpperW",              (SYSCALL)0,                       0 },
          235  +#endif
          236  +
          237  +#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
          238  +
          239  +  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
          240  +
          241  +#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
          242  +
          243  +#if defined(SQLITE_WIN32_HAS_ANSI)
          244  +  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
          245  +#else
          246  +  { "CreateFileA",             (SYSCALL)0,                       0 },
          247  +#endif
          248  +
          249  +#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
          250  +        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
          251  +
          252  +#if defined(SQLITE_WIN32_HAS_WIDE)
          253  +  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
          254  +#else
          255  +  { "CreateFileW",             (SYSCALL)0,                       0 },
          256  +#endif
          257  +
          258  +#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
          259  +        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
          260  +
          261  +  { "CreateFileMapping",       (SYSCALL)CreateFileMapping,       0 },
          262  +
          263  +#define osCreateFileMapping ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
          264  +        DWORD,DWORD,DWORD,LPCTSTR))aSyscall[6].pCurrent)
          265  +
          266  +#if defined(SQLITE_WIN32_HAS_WIDE)
          267  +  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
          268  +#else
          269  +  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
          270  +#endif
          271  +
          272  +#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
          273  +        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
          274  +
          275  +#if defined(SQLITE_WIN32_HAS_WIDE)
          276  +  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
          277  +#else
          278  +  { "CreateMutexW",            (SYSCALL)0,                       0 },
          279  +#endif
          280  +
          281  +#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
          282  +        LPCWSTR))aSyscall[8].pCurrent)
          283  +
          284  +#if defined(SQLITE_WIN32_HAS_ANSI)
          285  +  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
          286  +#else
          287  +  { "DeleteFileA",             (SYSCALL)0,                       0 },
          288  +#endif
          289  +
          290  +#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
          291  +
          292  +#if defined(SQLITE_WIN32_HAS_WIDE)
          293  +  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
          294  +#else
          295  +  { "DeleteFileW",             (SYSCALL)0,                       0 },
          296  +#endif
          297  +
          298  +#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
          299  +
          300  +#if SQLITE_OS_WINCE
          301  +  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
          302  +#else
          303  +  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
          304  +#endif
          305  +
          306  +#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
          307  +        LPFILETIME))aSyscall[11].pCurrent)
          308  +
          309  +#if SQLITE_OS_WINCE
          310  +  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
          311  +#else
          312  +  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
          313  +#endif
          314  +
          315  +#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
          316  +        LPSYSTEMTIME))aSyscall[12].pCurrent)
          317  +
          318  +  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
          319  +
          320  +#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
          321  +
          322  +#if defined(SQLITE_WIN32_HAS_ANSI)
          323  +  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
          324  +#else
          325  +  { "FormatMessageA",          (SYSCALL)0,                       0 },
          326  +#endif
          327  +
          328  +#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
          329  +        DWORD,va_list*))aSyscall[14].pCurrent)
          330  +
          331  +#if defined(SQLITE_WIN32_HAS_WIDE)
          332  +  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
          333  +#else
          334  +  { "FormatMessageW",          (SYSCALL)0,                       0 },
          335  +#endif
          336  +
          337  +#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
          338  +        DWORD,va_list*))aSyscall[15].pCurrent)
          339  +
          340  +  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
          341  +
          342  +#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
          343  +
          344  +  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
          345  +
          346  +#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
          347  +
          348  +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
          349  +  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
          350  +#else
          351  +  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
          352  +#endif
          353  +
          354  +#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
          355  +        LPDWORD))aSyscall[18].pCurrent)
          356  +
          357  +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
          358  +  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
          359  +#else
          360  +  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
          361  +#endif
          362  +
          363  +#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
          364  +        LPDWORD))aSyscall[19].pCurrent)
          365  +
          366  +#if defined(SQLITE_WIN32_HAS_ANSI)
          367  +  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
          368  +#else
          369  +  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
          370  +#endif
          371  +
          372  +#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
          373  +
          374  +#if defined(SQLITE_WIN32_HAS_WIDE)
          375  +  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
          376  +#else
          377  +  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
          378  +#endif
          379  +
          380  +#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
          381  +
          382  +#if defined(SQLITE_WIN32_HAS_WIDE)
          383  +  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
          384  +#else
          385  +  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
          386  +#endif
          387  +
          388  +#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
          389  +        LPVOID))aSyscall[22].pCurrent)
          390  +
          391  +  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
          392  +
          393  +#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
          394  +
          395  +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
          396  +  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
          397  +#else
          398  +  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
          399  +#endif
          400  +
          401  +#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
          402  +        LPSTR*))aSyscall[24].pCurrent)
          403  +
          404  +#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
          405  +  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
          406  +#else
          407  +  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
          408  +#endif
          409  +
          410  +#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
          411  +        LPWSTR*))aSyscall[25].pCurrent)
          412  +
          413  +  { "GetLastError",            (SYSCALL)GetLastError,            0 },
          414  +
          415  +#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
          416  +
          417  +#if SQLITE_OS_WINCE
          418  +  /* The GetProcAddressA() routine is only available on Windows CE. */
          419  +  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
          420  +#else
          421  +  /* All other Windows platforms expect GetProcAddress() to take
          422  +  ** an ANSI string regardless of the _UNICODE setting */
          423  +  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
          424  +#endif
          425  +
          426  +#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
          427  +        LPCSTR))aSyscall[27].pCurrent)
          428  +
          429  +  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
          430  +
          431  +#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
          432  +
          433  +  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
          434  +
          435  +#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
          436  +
          437  +#if !SQLITE_OS_WINCE
          438  +  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
          439  +#else
          440  +  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
          441  +#endif
          442  +
          443  +#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
          444  +        LPFILETIME))aSyscall[30].pCurrent)
          445  +
          446  +#if defined(SQLITE_WIN32_HAS_ANSI)
          447  +  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
          448  +#else
          449  +  { "GetTempPathA",            (SYSCALL)0,                       0 },
          450  +#endif
          451  +
          452  +#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
          453  +
          454  +#if defined(SQLITE_WIN32_HAS_WIDE)
          455  +  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
          456  +#else
          457  +  { "GetTempPathW",            (SYSCALL)0,                       0 },
          458  +#endif
          459  +
          460  +#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
          461  +
          462  +  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
          463  +
          464  +#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
          465  +
          466  +#if defined(SQLITE_WIN32_HAS_ANSI)
          467  +  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
          468  +#else
          469  +  { "GetVersionExA",           (SYSCALL)0,                       0 },
          470  +#endif
          471  +
          472  +#define osGetVersionExA ((BOOL(WINAPI*)( \
          473  +        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
          474  +
          475  +  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
          476  +
          477  +#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
          478  +        SIZE_T))aSyscall[35].pCurrent)
          479  +
          480  +  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
          481  +
          482  +#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
          483  +        SIZE_T))aSyscall[36].pCurrent)
          484  +
          485  +  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
          486  +
          487  +#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
          488  +
          489  +  { "HeapFree",                (SYSCALL)HeapFree,                0 },
          490  +
          491  +#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
          492  +
          493  +  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
          494  +
          495  +#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
          496  +        SIZE_T))aSyscall[39].pCurrent)
          497  +
          498  +  { "HeapSize",                (SYSCALL)HeapSize,                0 },
          499  +
          500  +#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
          501  +        LPCVOID))aSyscall[40].pCurrent)
          502  +
          503  +  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
          504  +
          505  +#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
          506  +        LPCVOID))aSyscall[41].pCurrent)
          507  +
          508  +#if defined(SQLITE_WIN32_HAS_ANSI)
          509  +  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
          510  +#else
          511  +  { "LoadLibraryA",            (SYSCALL)0,                       0 },
          512  +#endif
          513  +
          514  +#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
          515  +
          516  +#if defined(SQLITE_WIN32_HAS_WIDE)
          517  +  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
          518  +#else
          519  +  { "LoadLibraryW",            (SYSCALL)0,                       0 },
          520  +#endif
          521  +
          522  +#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
          523  +
          524  +  { "LocalFree",               (SYSCALL)LocalFree,               0 },
          525  +
          526  +#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
          527  +
          528  +#if !SQLITE_OS_WINCE
          529  +  { "LockFile",                (SYSCALL)LockFile,                0 },
          530  +
          531  +#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
          532  +        DWORD))aSyscall[45].pCurrent)
          533  +#else
          534  +  { "LockFile",                (SYSCALL)0,                       0 },
          535  +#endif
          536  +
          537  +#if !SQLITE_OS_WINCE
          538  +  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
          539  +
          540  +#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
          541  +        LPOVERLAPPED))aSyscall[46].pCurrent)
          542  +#else
          543  +  { "LockFileEx",              (SYSCALL)0,                       0 },
          544  +#endif
          545  +
          546  +  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
          547  +
          548  +#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
          549  +        SIZE_T))aSyscall[47].pCurrent)
          550  +
          551  +  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
          552  +
          553  +#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
          554  +        int))aSyscall[48].pCurrent)
          555  +
          556  +  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
          557  +
          558  +#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
          559  +        LARGE_INTEGER*))aSyscall[49].pCurrent)
          560  +
          561  +  { "ReadFile",                (SYSCALL)ReadFile,                0 },
          562  +
          563  +#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
          564  +        LPOVERLAPPED))aSyscall[50].pCurrent)
          565  +
          566  +  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
          567  +
          568  +#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
          569  +
          570  +  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
          571  +
          572  +#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
          573  +        DWORD))aSyscall[52].pCurrent)
          574  +
          575  +  { "Sleep",                   (SYSCALL)Sleep,                   0 },
          576  +
          577  +#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
          578  +
          579  +  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
          580  +
          581  +#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
          582  +        LPFILETIME))aSyscall[54].pCurrent)
          583  +
          584  +#if !SQLITE_OS_WINCE
          585  +  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
          586  +
          587  +#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
          588  +        DWORD))aSyscall[55].pCurrent)
          589  +#else
          590  +  { "UnlockFile",              (SYSCALL)0,                       0 },
          591  +#endif
          592  +
          593  +#if !SQLITE_OS_WINCE
          594  +  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
          595  +
          596  +#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
          597  +        LPOVERLAPPED))aSyscall[56].pCurrent)
          598  +#else
          599  +  { "UnlockFileEx",            (SYSCALL)0,                       0 },
          600  +#endif
          601  +
          602  +  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
          603  +
          604  +#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
          605  +
          606  +  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
          607  +
          608  +#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
          609  +        LPCSTR,LPBOOL))aSyscall[58].pCurrent)
          610  +
          611  +  { "WriteFile",               (SYSCALL)WriteFile,               0 },
          612  +
          613  +#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
          614  +        LPOVERLAPPED))aSyscall[59].pCurrent)
          615  +
          616  +}; /* End of the overrideable system calls */
          617  +
          618  +/*
          619  +** This is the xSetSystemCall() method of sqlite3_vfs for all of the
          620  +** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
          621  +** system call pointer, or SQLITE_NOTFOUND if there is no configurable
          622  +** system call named zName.
          623  +*/
          624  +static int winSetSystemCall(
          625  +  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
          626  +  const char *zName,            /* Name of system call to override */
          627  +  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
          628  +){
          629  +  unsigned int i;
          630  +  int rc = SQLITE_NOTFOUND;
          631  +
          632  +  UNUSED_PARAMETER(pNotUsed);
          633  +  if( zName==0 ){
          634  +    /* If no zName is given, restore all system calls to their default
          635  +    ** settings and return NULL
          636  +    */
          637  +    rc = SQLITE_OK;
          638  +    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
          639  +      if( aSyscall[i].pDefault ){
          640  +        aSyscall[i].pCurrent = aSyscall[i].pDefault;
          641  +      }
          642  +    }
          643  +  }else{
          644  +    /* If zName is specified, operate on only the one system call
          645  +    ** specified.
          646  +    */
          647  +    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
          648  +      if( strcmp(zName, aSyscall[i].zName)==0 ){
          649  +        if( aSyscall[i].pDefault==0 ){
          650  +          aSyscall[i].pDefault = aSyscall[i].pCurrent;
          651  +        }
          652  +        rc = SQLITE_OK;
          653  +        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
          654  +        aSyscall[i].pCurrent = pNewFunc;
          655  +        break;
          656  +      }
          657  +    }
          658  +  }
          659  +  return rc;
          660  +}
          661  +
          662  +/*
          663  +** Return the value of a system call.  Return NULL if zName is not a
          664  +** recognized system call name.  NULL is also returned if the system call
          665  +** is currently undefined.
          666  +*/
          667  +static sqlite3_syscall_ptr winGetSystemCall(
          668  +  sqlite3_vfs *pNotUsed,
          669  +  const char *zName
          670  +){
          671  +  unsigned int i;
          672  +
          673  +  UNUSED_PARAMETER(pNotUsed);
          674  +  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
          675  +    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
          676  +  }
          677  +  return 0;
          678  +}
          679  +
          680  +/*
          681  +** Return the name of the first system call after zName.  If zName==NULL
          682  +** then return the name of the first system call.  Return NULL if zName
          683  +** is the last system call or if zName is not the name of a valid
          684  +** system call.
          685  +*/
          686  +static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
          687  +  int i = -1;
          688  +
          689  +  UNUSED_PARAMETER(p);
          690  +  if( zName ){
          691  +    for(i=0; i<ArraySize(aSyscall)-1; i++){
          692  +      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
          693  +    }
          694  +  }
          695  +  for(i++; i<ArraySize(aSyscall); i++){
          696  +    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
          697  +  }
          698  +  return 0;
          699  +}
   218    700   
   219    701   /*
   220    702   ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
   221    703   ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
   222    704   **
   223    705   ** Here is an interesting observation:  Win95, Win98, and WinME lack
   224    706   ** the LockFileEx() API.  But we can still statically link against that
................................................................................
   228    710   ** the LockFileEx() API.
   229    711   */
   230    712   #if SQLITE_OS_WINCE
   231    713   # define isNT()  (1)
   232    714   #else
   233    715     static int isNT(void){
   234    716       if( sqlite3_os_type==0 ){
   235         -      OSVERSIONINFO sInfo;
          717  +      OSVERSIONINFOA sInfo;
   236    718         sInfo.dwOSVersionInfoSize = sizeof(sInfo);
   237         -      GetVersionEx(&sInfo);
          719  +      osGetVersionExA(&sInfo);
   238    720         sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
   239    721       }
   240    722       return sqlite3_os_type==2;
   241    723     }
   242    724   #endif /* SQLITE_OS_WINCE */
   243    725   
   244    726   #ifdef SQLITE_WIN32_MALLOC
................................................................................
   250    732     void *p;
   251    733   
   252    734     winMemAssertMagic();
   253    735     hHeap = winMemGetHeap();
   254    736     assert( hHeap!=0 );
   255    737     assert( hHeap!=INVALID_HANDLE_VALUE );
   256    738   #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   257         -  assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
          739  +  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   258    740   #endif
   259    741     assert( nBytes>=0 );
   260         -  p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
          742  +  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   261    743     if( !p ){
   262    744       sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
   263         -        nBytes, GetLastError(), (void*)hHeap);
          745  +                nBytes, osGetLastError(), (void*)hHeap);
   264    746     }
   265    747     return p;
   266    748   }
   267    749   
   268    750   /*
   269    751   ** Free memory.
   270    752   */
................................................................................
   272    754     HANDLE hHeap;
   273    755   
   274    756     winMemAssertMagic();
   275    757     hHeap = winMemGetHeap();
   276    758     assert( hHeap!=0 );
   277    759     assert( hHeap!=INVALID_HANDLE_VALUE );
   278    760   #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   279         -  assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
          761  +  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   280    762   #endif
   281    763     if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
   282         -  if( !HeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
          764  +  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
   283    765       sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
   284         -        pPrior, GetLastError(), (void*)hHeap);
          766  +                pPrior, osGetLastError(), (void*)hHeap);
   285    767     }
   286    768   }
   287    769   
   288    770   /*
   289    771   ** Change the size of an existing memory allocation
   290    772   */
   291    773   static void *winMemRealloc(void *pPrior, int nBytes){
................................................................................
   293    775     void *p;
   294    776   
   295    777     winMemAssertMagic();
   296    778     hHeap = winMemGetHeap();
   297    779     assert( hHeap!=0 );
   298    780     assert( hHeap!=INVALID_HANDLE_VALUE );
   299    781   #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   300         -  assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
          782  +  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
   301    783   #endif
   302    784     assert( nBytes>=0 );
   303    785     if( !pPrior ){
   304         -    p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
          786  +    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
   305    787     }else{
   306         -    p = HeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
          788  +    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
   307    789     }
   308    790     if( !p ){
   309    791       sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
   310         -        pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, GetLastError(),
   311         -        (void*)hHeap);
          792  +                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
          793  +                (void*)hHeap);
   312    794     }
   313    795     return p;
   314    796   }
   315    797   
   316    798   /*
   317    799   ** Return the size of an outstanding allocation, in bytes.
   318    800   */
................................................................................
   321    803     SIZE_T n;
   322    804   
   323    805     winMemAssertMagic();
   324    806     hHeap = winMemGetHeap();
   325    807     assert( hHeap!=0 );
   326    808     assert( hHeap!=INVALID_HANDLE_VALUE );
   327    809   #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   328         -  assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
          810  +  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   329    811   #endif
   330    812     if( !p ) return 0;
   331         -  n = HeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
          813  +  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
   332    814     if( n==(SIZE_T)-1 ){
   333    815       sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
   334         -        p, GetLastError(), (void*)hHeap);
          816  +                p, osGetLastError(), (void*)hHeap);
   335    817       return 0;
   336    818     }
   337    819     return (int)n;
   338    820   }
   339    821   
   340    822   /*
   341    823   ** Round up a request size to the next valid allocation size.
................................................................................
   349    831   */
   350    832   static int winMemInit(void *pAppData){
   351    833     winMemData *pWinMemData = (winMemData *)pAppData;
   352    834   
   353    835     if( !pWinMemData ) return SQLITE_ERROR;
   354    836     assert( pWinMemData->magic==WINMEM_MAGIC );
   355    837     if( !pWinMemData->hHeap ){
   356         -    pWinMemData->hHeap = HeapCreate(SQLITE_WIN32_HEAP_FLAGS,
   357         -                                    SQLITE_WIN32_HEAP_INIT_SIZE,
   358         -                                    SQLITE_WIN32_HEAP_MAX_SIZE);
          838  +    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
          839  +                                      SQLITE_WIN32_HEAP_INIT_SIZE,
          840  +                                      SQLITE_WIN32_HEAP_MAX_SIZE);
   359    841       if( !pWinMemData->hHeap ){
   360    842         sqlite3_log(SQLITE_NOMEM,
   361    843             "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
   362         -          GetLastError(), SQLITE_WIN32_HEAP_FLAGS, SQLITE_WIN32_HEAP_INIT_SIZE,
   363         -          SQLITE_WIN32_HEAP_MAX_SIZE);
          844  +          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
          845  +          SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
   364    846         return SQLITE_NOMEM;
   365    847       }
   366    848       pWinMemData->bOwned = TRUE;
   367    849     }
   368    850     assert( pWinMemData->hHeap!=0 );
   369    851     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   370    852   #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   371         -  assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
          853  +  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   372    854   #endif
   373    855     return SQLITE_OK;
   374    856   }
   375    857   
   376    858   /*
   377    859   ** Deinitialize this module.
   378    860   */
................................................................................
   379    861   static void winMemShutdown(void *pAppData){
   380    862     winMemData *pWinMemData = (winMemData *)pAppData;
   381    863   
   382    864     if( !pWinMemData ) return;
   383    865     if( pWinMemData->hHeap ){
   384    866       assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
   385    867   #ifdef SQLITE_WIN32_MALLOC_VALIDATE
   386         -    assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
          868  +    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
   387    869   #endif
   388    870       if( pWinMemData->bOwned ){
   389         -      if( !HeapDestroy(pWinMemData->hHeap) ){
          871  +      if( !osHeapDestroy(pWinMemData->hHeap) ){
   390    872           sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
   391         -            GetLastError(), (void*)pWinMemData->hHeap);
          873  +                    osGetLastError(), (void*)pWinMemData->hHeap);
   392    874         }
   393    875         pWinMemData->bOwned = FALSE;
   394    876       }
   395    877       pWinMemData->hHeap = NULL;
   396    878     }
   397    879   }
   398    880   
................................................................................
   420    902   
   421    903   void sqlite3MemSetDefault(void){
   422    904     sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
   423    905   }
   424    906   #endif /* SQLITE_WIN32_MALLOC */
   425    907   
   426    908   /*
   427         -** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
          909  +** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
   428    910   **
   429    911   ** Space to hold the returned string is obtained from malloc.
   430    912   */
   431         -static WCHAR *utf8ToUnicode(const char *zFilename){
          913  +static LPWSTR utf8ToUnicode(const char *zFilename){
   432    914     int nChar;
   433         -  WCHAR *zWideFilename;
          915  +  LPWSTR zWideFilename;
   434    916   
   435         -  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
   436         -  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
          917  +  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
          918  +  if( nChar==0 ){
          919  +    return 0;
          920  +  }
          921  +  zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
   437    922     if( zWideFilename==0 ){
   438    923       return 0;
   439    924     }
   440         -  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
          925  +  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
          926  +                                nChar);
   441    927     if( nChar==0 ){
   442         -    free(zWideFilename);
          928  +    sqlite3_free(zWideFilename);
   443    929       zWideFilename = 0;
   444    930     }
   445    931     return zWideFilename;
   446    932   }
   447    933   
   448    934   /*
   449         -** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
   450         -** obtained from malloc().
          935  +** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
          936  +** obtained from sqlite3_malloc().
   451    937   */
   452         -static char *unicodeToUtf8(const WCHAR *zWideFilename){
          938  +static char *unicodeToUtf8(LPCWSTR zWideFilename){
   453    939     int nByte;
   454    940     char *zFilename;
   455    941   
   456         -  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
   457         -  zFilename = malloc( nByte );
          942  +  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
          943  +  if( nByte == 0 ){
          944  +    return 0;
          945  +  }
          946  +  zFilename = sqlite3_malloc( nByte );
   458    947     if( zFilename==0 ){
   459    948       return 0;
   460    949     }
   461         -  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
   462         -                              0, 0);
          950  +  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
          951  +                                0, 0);
   463    952     if( nByte == 0 ){
   464         -    free(zFilename);
          953  +    sqlite3_free(zFilename);
   465    954       zFilename = 0;
   466    955     }
   467    956     return zFilename;
   468    957   }
   469    958   
   470    959   /*
   471         -** Convert an ansi string to microsoft unicode, based on the
          960  +** Convert an ANSI string to Microsoft Unicode, based on the
   472    961   ** current codepage settings for file apis.
   473    962   ** 
   474    963   ** Space to hold the returned string is obtained
   475         -** from malloc.
          964  +** from sqlite3_malloc.
   476    965   */
   477         -static WCHAR *mbcsToUnicode(const char *zFilename){
          966  +static LPWSTR mbcsToUnicode(const char *zFilename){
   478    967     int nByte;
   479         -  WCHAR *zMbcsFilename;
   480         -  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
          968  +  LPWSTR zMbcsFilename;
          969  +  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   481    970   
   482         -  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
   483         -  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
          971  +  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
          972  +                                0)*sizeof(WCHAR);
          973  +  if( nByte==0 ){
          974  +    return 0;
          975  +  }
          976  +  zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );
   484    977     if( zMbcsFilename==0 ){
   485    978       return 0;
   486    979     }
   487         -  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
          980  +  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
          981  +                                nByte);
   488    982     if( nByte==0 ){
   489         -    free(zMbcsFilename);
          983  +    sqlite3_free(zMbcsFilename);
   490    984       zMbcsFilename = 0;
   491    985     }
   492    986     return zMbcsFilename;
   493    987   }
   494    988   
   495    989   /*
   496         -** Convert microsoft unicode to multibyte character string, based on the
   497         -** user's Ansi codepage.
          990  +** Convert Microsoft Unicode to multi-byte character string, based on the
          991  +** user's ANSI codepage.
   498    992   **
   499    993   ** Space to hold the returned string is obtained from
   500         -** malloc().
          994  +** sqlite3_malloc().
   501    995   */
   502         -static char *unicodeToMbcs(const WCHAR *zWideFilename){
          996  +static char *unicodeToMbcs(LPCWSTR zWideFilename){
   503    997     int nByte;
   504    998     char *zFilename;
   505         -  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
          999  +  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
   506   1000   
   507         -  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
   508         -  zFilename = malloc( nByte );
         1001  +  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
         1002  +  if( nByte == 0 ){
         1003  +    return 0;
         1004  +  }
         1005  +  zFilename = sqlite3_malloc( nByte );
   509   1006     if( zFilename==0 ){
   510   1007       return 0;
   511   1008     }
   512         -  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
   513         -                              0, 0);
         1009  +  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
         1010  +                                nByte, 0, 0);
   514   1011     if( nByte == 0 ){
   515         -    free(zFilename);
         1012  +    sqlite3_free(zFilename);
   516   1013       zFilename = 0;
   517   1014     }
   518   1015     return zFilename;
   519   1016   }
   520   1017   
   521   1018   /*
   522   1019   ** Convert multibyte character string to UTF-8.  Space to hold the
   523         -** returned string is obtained from malloc().
         1020  +** returned string is obtained from sqlite3_malloc().
   524   1021   */
   525   1022   char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
   526   1023     char *zFilenameUtf8;
   527         -  WCHAR *zTmpWide;
         1024  +  LPWSTR zTmpWide;
   528   1025   
   529   1026     zTmpWide = mbcsToUnicode(zFilename);
   530   1027     if( zTmpWide==0 ){
   531   1028       return 0;
   532   1029     }
   533   1030     zFilenameUtf8 = unicodeToUtf8(zTmpWide);
   534         -  free(zTmpWide);
         1031  +  sqlite3_free(zTmpWide);
   535   1032     return zFilenameUtf8;
   536   1033   }
   537   1034   
   538   1035   /*
   539   1036   ** Convert UTF-8 to multibyte character string.  Space to hold the 
   540         -** returned string is obtained from malloc().
         1037  +** returned string is obtained from sqlite3_malloc().
   541   1038   */
   542   1039   char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
   543   1040     char *zFilenameMbcs;
   544         -  WCHAR *zTmpWide;
         1041  +  LPWSTR zTmpWide;
   545   1042   
   546   1043     zTmpWide = utf8ToUnicode(zFilename);
   547   1044     if( zTmpWide==0 ){
   548   1045       return 0;
   549   1046     }
   550   1047     zFilenameMbcs = unicodeToMbcs(zTmpWide);
   551         -  free(zTmpWide);
         1048  +  sqlite3_free(zTmpWide);
   552   1049     return zFilenameMbcs;
   553   1050   }
   554   1051   
   555   1052   
   556   1053   /*
   557   1054   ** The return value of getLastErrorMsg
   558   1055   ** is zero if the error message fits in the buffer, or non-zero
   559   1056   ** otherwise (if the message was truncated).
   560   1057   */
   561         -static int getLastErrorMsg(int nBuf, char *zBuf){
         1058  +static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
   562   1059     /* FormatMessage returns 0 on failure.  Otherwise it
   563   1060     ** returns the number of TCHARs written to the output
   564   1061     ** buffer, excluding the terminating null char.
   565   1062     */
   566         -  DWORD error = GetLastError();
   567   1063     DWORD dwLen = 0;
   568   1064     char *zOut = 0;
   569   1065   
   570   1066     if( isNT() ){
   571         -    WCHAR *zTempWide = NULL;
   572         -    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
   573         -                           NULL,
   574         -                           error,
   575         -                           0,
   576         -                           (LPWSTR) &zTempWide,
   577         -                           0,
   578         -                           0);
         1067  +    LPWSTR zTempWide = NULL;
         1068  +    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
         1069  +                             FORMAT_MESSAGE_FROM_SYSTEM |
         1070  +                             FORMAT_MESSAGE_IGNORE_INSERTS,
         1071  +                             NULL,
         1072  +                             lastErrno,
         1073  +                             0,
         1074  +                             (LPWSTR) &zTempWide,
         1075  +                             0,
         1076  +                             0);
   579   1077       if( dwLen > 0 ){
   580   1078         /* allocate a buffer and convert to UTF8 */
         1079  +      sqlite3BeginBenignMalloc();
   581   1080         zOut = unicodeToUtf8(zTempWide);
         1081  +      sqlite3EndBenignMalloc();
   582   1082         /* free the system buffer allocated by FormatMessage */
   583         -      LocalFree(zTempWide);
         1083  +      osLocalFree(zTempWide);
   584   1084       }
   585   1085   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
   586         -** Since the ASCII version of these Windows API do not exist for WINCE,
         1086  +** Since the ANSI version of these Windows API do not exist for WINCE,
   587   1087   ** it's important to not reference them for WINCE builds.
   588   1088   */
   589   1089   #if SQLITE_OS_WINCE==0
   590   1090     }else{
   591   1091       char *zTemp = NULL;
   592         -    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
   593         -                           NULL,
   594         -                           error,
   595         -                           0,
   596         -                           (LPSTR) &zTemp,
   597         -                           0,
   598         -                           0);
         1092  +    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
         1093  +                             FORMAT_MESSAGE_FROM_SYSTEM |
         1094  +                             FORMAT_MESSAGE_IGNORE_INSERTS,
         1095  +                             NULL,
         1096  +                             lastErrno,
         1097  +                             0,
         1098  +                             (LPSTR) &zTemp,
         1099  +                             0,
         1100  +                             0);
   599   1101       if( dwLen > 0 ){
   600   1102         /* allocate a buffer and convert to UTF8 */
         1103  +      sqlite3BeginBenignMalloc();
   601   1104         zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
         1105  +      sqlite3EndBenignMalloc();
   602   1106         /* free the system buffer allocated by FormatMessage */
   603         -      LocalFree(zTemp);
         1107  +      osLocalFree(zTemp);
   604   1108       }
   605   1109   #endif
   606   1110     }
   607   1111     if( 0 == dwLen ){
   608         -    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
         1112  +    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
   609   1113     }else{
   610   1114       /* copy a maximum of nBuf chars to output buffer */
   611   1115       sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
   612   1116       /* free the UTF8 buffer */
   613         -    free(zOut);
         1117  +    sqlite3_free(zOut);
   614   1118     }
   615   1119     return 0;
   616   1120   }
   617   1121   
   618   1122   /*
   619   1123   **
   620   1124   ** This function - winLogErrorAtLine() - is only ever called via the macro
................................................................................
   626   1130   ** FormatMessage.
   627   1131   **
   628   1132   ** The first argument passed to the macro should be the error code that
   629   1133   ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
   630   1134   ** The two subsequent arguments should be the name of the OS function that
   631   1135   ** failed and the the associated file-system path, if any.
   632   1136   */
   633         -#define winLogError(a,b,c)     winLogErrorAtLine(a,b,c,__LINE__)
         1137  +#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
   634   1138   static int winLogErrorAtLine(
   635   1139     int errcode,                    /* SQLite error code */
         1140  +  DWORD lastErrno,                /* Win32 last error */
   636   1141     const char *zFunc,              /* Name of OS function that failed */
   637   1142     const char *zPath,              /* File path associated with error */
   638   1143     int iLine                       /* Source line number where error occurred */
   639   1144   ){
   640   1145     char zMsg[500];                 /* Human readable error text */
   641   1146     int i;                          /* Loop counter */
   642         -  DWORD iErrno = GetLastError();  /* Error code */
   643   1147   
   644   1148     zMsg[0] = 0;
   645         -  getLastErrorMsg(sizeof(zMsg), zMsg);
         1149  +  getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
   646   1150     assert( errcode!=SQLITE_OK );
   647   1151     if( zPath==0 ) zPath = "";
   648   1152     for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
   649   1153     zMsg[i] = 0;
   650   1154     sqlite3_log(errcode,
   651   1155         "os_win.c:%d: (%d) %s(%s) - %s",
   652         -      iLine, iErrno, zFunc, zPath, zMsg
         1156  +      iLine, lastErrno, zFunc, zPath, zMsg
   653   1157     );
   654   1158   
   655   1159     return errcode;
   656   1160   }
   657   1161   
   658   1162   /*
   659   1163   ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
................................................................................
   671   1175   static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
   672   1176   
   673   1177   /*
   674   1178   ** If a ReadFile() or WriteFile() error occurs, invoke this routine
   675   1179   ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
   676   1180   ** to give up with an error.
   677   1181   */
   678         -static int retryIoerr(int *pnRetry){
   679         -  DWORD e;
         1182  +static int retryIoerr(int *pnRetry, DWORD *pError){
         1183  +  DWORD e = osGetLastError();
   680   1184     if( *pnRetry>=win32IoerrRetry ){
         1185  +    if( pError ){
         1186  +      *pError = e;
         1187  +    }
   681   1188       return 0;
   682   1189     }
   683         -  e = GetLastError();
   684   1190     if( e==ERROR_ACCESS_DENIED ||
   685   1191         e==ERROR_LOCK_VIOLATION ||
   686   1192         e==ERROR_SHARING_VIOLATION ){
   687         -    Sleep(win32IoerrRetryDelay*(1+*pnRetry));
         1193  +    osSleep(win32IoerrRetryDelay*(1+*pnRetry));
   688   1194       ++*pnRetry;
   689   1195       return 1;
   690   1196     }
         1197  +  if( pError ){
         1198  +    *pError = e;
         1199  +  }
   691   1200     return 0;
   692   1201   }
   693   1202   
   694   1203   /*
   695   1204   ** Log a I/O error retry episode.
   696   1205   */
   697   1206   static void logIoerr(int nRetry){
................................................................................
   704   1213   }
   705   1214   
   706   1215   #if SQLITE_OS_WINCE
   707   1216   /*************************************************************************
   708   1217   ** This section contains code for WinCE only.
   709   1218   */
   710   1219   /*
   711         -** WindowsCE does not have a localtime() function.  So create a
         1220  +** Windows CE does not have a localtime() function.  So create a
   712   1221   ** substitute.
   713   1222   */
   714   1223   #include <time.h>
   715   1224   struct tm *__cdecl localtime(const time_t *t)
   716   1225   {
   717   1226     static struct tm y;
   718   1227     FILETIME uTm, lTm;
   719   1228     SYSTEMTIME pTm;
   720   1229     sqlite3_int64 t64;
   721   1230     t64 = *t;
   722   1231     t64 = (t64 + 11644473600)*10000000;
   723   1232     uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
   724   1233     uTm.dwHighDateTime= (DWORD)(t64 >> 32);
   725         -  FileTimeToLocalFileTime(&uTm,&lTm);
   726         -  FileTimeToSystemTime(&lTm,&pTm);
         1234  +  osFileTimeToLocalFileTime(&uTm,&lTm);
         1235  +  osFileTimeToSystemTime(&lTm,&pTm);
   727   1236     y.tm_year = pTm.wYear - 1900;
   728   1237     y.tm_mon = pTm.wMonth - 1;
   729   1238     y.tm_wday = pTm.wDayOfWeek;
   730   1239     y.tm_mday = pTm.wDay;
   731   1240     y.tm_hour = pTm.wHour;
   732   1241     y.tm_min = pTm.wMinute;
   733   1242     y.tm_sec = pTm.wSecond;
   734   1243     return &y;
   735   1244   }
   736   1245   
   737         -/* This will never be called, but defined to make the code compile */
   738         -#define GetTempPathA(a,b)
   739         -
   740         -#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
   741         -#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
   742         -#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
   743         -
   744   1246   #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
   745   1247   
   746   1248   /*
   747   1249   ** Acquire a lock on the handle h
   748   1250   */
   749   1251   static void winceMutexAcquire(HANDLE h){
   750   1252      DWORD dwErr;
................................................................................
   758   1260   #define winceMutexRelease(h) ReleaseMutex(h)
   759   1261   
   760   1262   /*
   761   1263   ** Create the mutex and shared memory used for locking in the file
   762   1264   ** descriptor pFile
   763   1265   */
   764   1266   static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
   765         -  WCHAR *zTok;
   766         -  WCHAR *zName = utf8ToUnicode(zFilename);
         1267  +  LPWSTR zTok;
         1268  +  LPWSTR zName;
   767   1269     BOOL bInit = TRUE;
         1270  +
         1271  +  zName = utf8ToUnicode(zFilename);
         1272  +  if( zName==0 ){
         1273  +    /* out of memory */
         1274  +    return FALSE;
         1275  +  }
   768   1276   
   769   1277     /* Initialize the local lockdata */
   770         -  ZeroMemory(&pFile->local, sizeof(pFile->local));
         1278  +  memset(&pFile->local, 0, sizeof(pFile->local));
   771   1279   
   772   1280     /* Replace the backslashes from the filename and lowercase it
   773   1281     ** to derive a mutex name. */
   774         -  zTok = CharLowerW(zName);
         1282  +  zTok = osCharLowerW(zName);
   775   1283     for (;*zTok;zTok++){
   776   1284       if (*zTok == '\\') *zTok = '_';
   777   1285     }
   778   1286   
   779   1287     /* Create/open the named mutex */
   780         -  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
         1288  +  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
   781   1289     if (!pFile->hMutex){
   782         -    pFile->lastErrno = GetLastError();
   783         -    winLogError(SQLITE_ERROR, "winceCreateLock1", zFilename);
   784         -    free(zName);
         1290  +    pFile->lastErrno = osGetLastError();
         1291  +    winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
         1292  +    sqlite3_free(zName);
   785   1293       return FALSE;
   786   1294     }
   787   1295   
   788   1296     /* Acquire the mutex before continuing */
   789   1297     winceMutexAcquire(pFile->hMutex);
   790   1298     
   791   1299     /* Since the names of named mutexes, semaphores, file mappings etc are 
   792   1300     ** case-sensitive, take advantage of that by uppercasing the mutex name
   793   1301     ** and using that as the shared filemapping name.
   794   1302     */
   795         -  CharUpperW(zName);
   796         -  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
   797         -                                       PAGE_READWRITE, 0, sizeof(winceLock),
   798         -                                       zName);  
         1303  +  osCharUpperW(zName);
         1304  +  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
         1305  +                                        PAGE_READWRITE, 0, sizeof(winceLock),
         1306  +                                        zName);  
   799   1307   
   800   1308     /* Set a flag that indicates we're the first to create the memory so it 
   801   1309     ** must be zero-initialized */
   802         -  if (GetLastError() == ERROR_ALREADY_EXISTS){
         1310  +  if (osGetLastError() == ERROR_ALREADY_EXISTS){
   803   1311       bInit = FALSE;
   804   1312     }
   805   1313   
   806         -  free(zName);
         1314  +  sqlite3_free(zName);
   807   1315   
   808   1316     /* If we succeeded in making the shared memory handle, map it. */
   809   1317     if (pFile->hShared){
   810         -    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
         1318  +    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
   811   1319                FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
   812   1320       /* If mapping failed, close the shared memory handle and erase it */
   813   1321       if (!pFile->shared){
   814         -      pFile->lastErrno = GetLastError();
   815         -      winLogError(SQLITE_ERROR, "winceCreateLock2", zFilename);
   816         -      CloseHandle(pFile->hShared);
         1322  +      pFile->lastErrno = osGetLastError();
         1323  +      winLogError(SQLITE_ERROR, pFile->lastErrno,
         1324  +               "winceCreateLock2", zFilename);
         1325  +      osCloseHandle(pFile->hShared);
   817   1326         pFile->hShared = NULL;
   818   1327       }
   819   1328     }
   820   1329   
   821   1330     /* If shared memory could not be created, then close the mutex and fail */
   822   1331     if (pFile->hShared == NULL){
   823   1332       winceMutexRelease(pFile->hMutex);
   824         -    CloseHandle(pFile->hMutex);
         1333  +    osCloseHandle(pFile->hMutex);
   825   1334       pFile->hMutex = NULL;
   826   1335       return FALSE;
   827   1336     }
   828   1337     
   829   1338     /* Initialize the shared memory if we're supposed to */
   830   1339     if (bInit) {
   831         -    ZeroMemory(pFile->shared, sizeof(winceLock));
         1340  +    memset(pFile->shared, 0, sizeof(winceLock));
   832   1341     }
   833   1342   
   834   1343     winceMutexRelease(pFile->hMutex);
   835   1344     return TRUE;
   836   1345   }
   837   1346   
   838   1347   /*
................................................................................
   855   1364         pFile->shared->bPending = FALSE;
   856   1365       }
   857   1366       if (pFile->local.bExclusive){
   858   1367         pFile->shared->bExclusive = FALSE;
   859   1368       }
   860   1369   
   861   1370       /* De-reference and close our copy of the shared memory handle */
   862         -    UnmapViewOfFile(pFile->shared);
   863         -    CloseHandle(pFile->hShared);
         1371  +    osUnmapViewOfFile(pFile->shared);
         1372  +    osCloseHandle(pFile->hShared);
   864   1373   
   865   1374       /* Done with the mutex */
   866   1375       winceMutexRelease(pFile->hMutex);    
   867         -    CloseHandle(pFile->hMutex);
         1376  +    osCloseHandle(pFile->hMutex);
   868   1377       pFile->hMutex = NULL;
   869   1378     }
   870   1379   }
   871   1380   
   872   1381   /* 
   873         -** An implementation of the LockFile() API of windows for wince
         1382  +** An implementation of the LockFile() API of Windows for CE
   874   1383   */
   875   1384   static BOOL winceLockFile(
   876   1385     HANDLE *phFile,
   877   1386     DWORD dwFileOffsetLow,
   878   1387     DWORD dwFileOffsetHigh,
   879   1388     DWORD nNumberOfBytesToLockLow,
   880   1389     DWORD nNumberOfBytesToLockHigh
................................................................................
   930   1439     }
   931   1440   
   932   1441     winceMutexRelease(pFile->hMutex);
   933   1442     return bReturn;
   934   1443   }
   935   1444   
   936   1445   /*
   937         -** An implementation of the UnlockFile API of windows for wince
         1446  +** An implementation of the UnlockFile API of Windows for CE
   938   1447   */
   939   1448   static BOOL winceUnlockFile(
   940   1449     HANDLE *phFile,
   941   1450     DWORD dwFileOffsetLow,
   942   1451     DWORD dwFileOffsetHigh,
   943   1452     DWORD nNumberOfBytesToUnlockLow,
   944   1453     DWORD nNumberOfBytesToUnlockHigh
................................................................................
   992   1501     }
   993   1502   
   994   1503     winceMutexRelease(pFile->hMutex);
   995   1504     return bReturn;
   996   1505   }
   997   1506   
   998   1507   /*
   999         -** An implementation of the LockFileEx() API of windows for wince
         1508  +** An implementation of the LockFileEx() API of Windows for CE
  1000   1509   */
  1001   1510   static BOOL winceLockFileEx(
  1002   1511     HANDLE *phFile,
  1003   1512     DWORD dwFlags,
  1004   1513     DWORD dwReserved,
  1005   1514     DWORD nNumberOfBytesToLockLow,
  1006   1515     DWORD nNumberOfBytesToLockHigh,
................................................................................
  1025   1534   
  1026   1535   /*****************************************************************************
  1027   1536   ** The next group of routines implement the I/O methods specified
  1028   1537   ** by the sqlite3_io_methods object.
  1029   1538   ******************************************************************************/
  1030   1539   
  1031   1540   /*
  1032         -** Some microsoft compilers lack this definition.
         1541  +** Some Microsoft compilers lack this definition.
  1033   1542   */
  1034   1543   #ifndef INVALID_SET_FILE_POINTER
  1035   1544   # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  1036   1545   #endif
  1037   1546   
  1038   1547   /*
  1039   1548   ** Move the current position of the file handle passed as the first 
................................................................................
  1040   1549   ** argument to offset iOffset within the file. If successful, return 0. 
  1041   1550   ** Otherwise, set pFile->lastErrno and return non-zero.
  1042   1551   */
  1043   1552   static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
  1044   1553     LONG upperBits;                 /* Most sig. 32 bits of new offset */
  1045   1554     LONG lowerBits;                 /* Least sig. 32 bits of new offset */
  1046   1555     DWORD dwRet;                    /* Value returned by SetFilePointer() */
         1556  +  DWORD lastErrno;                /* Value returned by GetLastError() */
  1047   1557   
  1048   1558     upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  1049   1559     lowerBits = (LONG)(iOffset & 0xffffffff);
  1050   1560   
  1051   1561     /* API oddity: If successful, SetFilePointer() returns a dword 
  1052   1562     ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  1053   1563     ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
  1054   1564     ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
  1055   1565     ** whether an error has actually occured, it is also necessary to call 
  1056   1566     ** GetLastError().
  1057   1567     */
  1058         -  dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  1059         -  if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
  1060         -    pFile->lastErrno = GetLastError();
  1061         -    winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile->zPath);
         1568  +  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
         1569  +
         1570  +  if( (dwRet==INVALID_SET_FILE_POINTER
         1571  +      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
         1572  +    pFile->lastErrno = lastErrno;
         1573  +    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
         1574  +             "seekWinFile", pFile->zPath);
  1062   1575       return 1;
  1063   1576     }
  1064   1577   
  1065   1578     return 0;
  1066   1579   }
  1067   1580   
  1068   1581   /*
  1069   1582   ** Close a file.
  1070   1583   **
  1071   1584   ** It is reported that an attempt to close a handle might sometimes
  1072         -** fail.  This is a very unreasonable result, but windows is notorious
         1585  +** fail.  This is a very unreasonable result, but Windows is notorious
  1073   1586   ** for being unreasonable so I do not doubt that it might happen.  If
  1074   1587   ** the close fails, we pause for 100 milliseconds and try again.  As
  1075   1588   ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  1076   1589   ** giving up and returning an error.
  1077   1590   */
  1078   1591   #define MX_CLOSE_ATTEMPT 3
  1079   1592   static int winClose(sqlite3_file *id){
................................................................................
  1080   1593     int rc, cnt = 0;
  1081   1594     winFile *pFile = (winFile*)id;
  1082   1595   
  1083   1596     assert( id!=0 );
  1084   1597     assert( pFile->pShm==0 );
  1085   1598     OSTRACE(("CLOSE %d\n", pFile->h));
  1086   1599     do{
  1087         -    rc = CloseHandle(pFile->h);
         1600  +    rc = osCloseHandle(pFile->h);
  1088   1601       /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  1089         -  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
         1602  +  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (osSleep(100), 1) );
  1090   1603   #if SQLITE_OS_WINCE
  1091   1604   #define WINCE_DELETION_ATTEMPTS 3
  1092   1605     winceDestroyLock(pFile);
  1093   1606     if( pFile->zDeleteOnClose ){
  1094   1607       int cnt = 0;
  1095   1608       while(
  1096         -           DeleteFileW(pFile->zDeleteOnClose)==0
  1097         -        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
         1609  +           osDeleteFileW(pFile->zDeleteOnClose)==0
         1610  +        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
  1098   1611           && cnt++ < WINCE_DELETION_ATTEMPTS
  1099   1612       ){
  1100         -       Sleep(100);  /* Wait a little before trying again */
         1613  +       osSleep(100);  /* Wait a little before trying again */
  1101   1614       }
  1102         -    free(pFile->zDeleteOnClose);
         1615  +    sqlite3_free(pFile->zDeleteOnClose);
  1103   1616     }
  1104   1617   #endif
  1105   1618     OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
  1106   1619     OpenCounter(-1);
  1107   1620     return rc ? SQLITE_OK
  1108         -            : winLogError(SQLITE_IOERR_CLOSE, "winClose", pFile->zPath);
         1621  +            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
         1622  +                          "winClose", pFile->zPath);
  1109   1623   }
  1110   1624   
  1111   1625   /*
  1112   1626   ** Read data from a file into a buffer.  Return SQLITE_OK if all
  1113   1627   ** bytes were read successfully and SQLITE_IOERR if anything goes
  1114   1628   ** wrong.
  1115   1629   */
................................................................................
  1126   1640     assert( id!=0 );
  1127   1641     SimulateIOError(return SQLITE_IOERR_READ);
  1128   1642     OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
  1129   1643   
  1130   1644     if( seekWinFile(pFile, offset) ){
  1131   1645       return SQLITE_FULL;
  1132   1646     }
  1133         -  while( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  1134         -    if( retryIoerr(&nRetry) ) continue;
  1135         -    pFile->lastErrno = GetLastError();
  1136         -    return winLogError(SQLITE_IOERR_READ, "winRead", pFile->zPath);
         1647  +  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
         1648  +    DWORD lastErrno;
         1649  +    if( retryIoerr(&nRetry, &lastErrno) ) continue;
         1650  +    pFile->lastErrno = lastErrno;
         1651  +    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
         1652  +             "winRead", pFile->zPath);
  1137   1653     }
  1138   1654     logIoerr(nRetry);
  1139   1655     if( nRead<(DWORD)amt ){
  1140   1656       /* Unread parts of the buffer must be zero-filled */
  1141   1657       memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  1142   1658       return SQLITE_IOERR_SHORT_READ;
  1143   1659     }
................................................................................
  1167   1683     OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
  1168   1684   
  1169   1685     rc = seekWinFile(pFile, offset);
  1170   1686     if( rc==0 ){
  1171   1687       u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
  1172   1688       int nRem = amt;               /* Number of bytes yet to be written */
  1173   1689       DWORD nWrite;                 /* Bytes written by each WriteFile() call */
         1690  +    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
  1174   1691   
  1175   1692       while( nRem>0 ){
  1176         -      if( !WriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  1177         -        if( retryIoerr(&nRetry) ) continue;
         1693  +      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
         1694  +        if( retryIoerr(&nRetry, &lastErrno) ) continue;
  1178   1695           break;
  1179   1696         }
  1180   1697         if( nWrite<=0 ) break;
  1181   1698         aRem += nWrite;
  1182   1699         nRem -= nWrite;
  1183   1700       }
  1184   1701       if( nRem>0 ){
  1185         -      pFile->lastErrno = GetLastError();
         1702  +      pFile->lastErrno = lastErrno;
  1186   1703         rc = 1;
  1187   1704       }
  1188   1705     }
  1189   1706   
  1190   1707     if( rc ){
  1191   1708       if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  1192   1709          || ( pFile->lastErrno==ERROR_DISK_FULL )){
  1193   1710         return SQLITE_FULL;
  1194   1711       }
  1195         -    return winLogError(SQLITE_IOERR_WRITE, "winWrite", pFile->zPath);
         1712  +    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
         1713  +             "winWrite", pFile->zPath);
  1196   1714     }else{
  1197   1715       logIoerr(nRetry);
  1198   1716     }
  1199   1717     return SQLITE_OK;
  1200   1718   }
  1201   1719   
  1202   1720   /*
................................................................................
  1218   1736     */
  1219   1737     if( pFile->szChunk>0 ){
  1220   1738       nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  1221   1739     }
  1222   1740   
  1223   1741     /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  1224   1742     if( seekWinFile(pFile, nByte) ){
  1225         -    rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate1", pFile->zPath);
  1226         -  }else if( 0==SetEndOfFile(pFile->h) ){
  1227         -    pFile->lastErrno = GetLastError();
  1228         -    rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate2", pFile->zPath);
         1743  +    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
         1744  +             "winTruncate1", pFile->zPath);
         1745  +  }else if( 0==osSetEndOfFile(pFile->h) ){
         1746  +    pFile->lastErrno = osGetLastError();
         1747  +    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
         1748  +             "winTruncate2", pFile->zPath);
  1229   1749     }
  1230   1750   
  1231   1751     OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
  1232   1752     return rc;
  1233   1753   }
  1234   1754   
  1235   1755   #ifdef SQLITE_TEST
................................................................................
  1286   1806   
  1287   1807     /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  1288   1808     ** no-op
  1289   1809     */
  1290   1810   #ifdef SQLITE_NO_SYNC
  1291   1811     return SQLITE_OK;
  1292   1812   #else
  1293         -  rc = FlushFileBuffers(pFile->h);
         1813  +  rc = osFlushFileBuffers(pFile->h);
  1294   1814     SimulateIOError( rc=FALSE );
  1295   1815     if( rc ){
  1296   1816       return SQLITE_OK;
  1297   1817     }else{
  1298         -    pFile->lastErrno = GetLastError();
  1299         -    return winLogError(SQLITE_IOERR_FSYNC, "winSync", pFile->zPath);
         1818  +    pFile->lastErrno = osGetLastError();
         1819  +    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
         1820  +             "winSync", pFile->zPath);
  1300   1821     }
  1301   1822   #endif
  1302   1823   }
  1303   1824   
  1304   1825   /*
  1305   1826   ** Determine the current size of a file in bytes
  1306   1827   */
  1307   1828   static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  1308   1829     DWORD upperBits;
  1309   1830     DWORD lowerBits;
  1310   1831     winFile *pFile = (winFile*)id;
  1311         -  DWORD error;
         1832  +  DWORD lastErrno;
  1312   1833   
  1313   1834     assert( id!=0 );
  1314   1835     SimulateIOError(return SQLITE_IOERR_FSTAT);
  1315         -  lowerBits = GetFileSize(pFile->h, &upperBits);
         1836  +  lowerBits = osGetFileSize(pFile->h, &upperBits);
  1316   1837     if(   (lowerBits == INVALID_FILE_SIZE)
  1317         -     && ((error = GetLastError()) != NO_ERROR) )
         1838  +     && ((lastErrno = osGetLastError())!=NO_ERROR) )
  1318   1839     {
  1319         -    pFile->lastErrno = error;
  1320         -    return winLogError(SQLITE_IOERR_FSTAT, "winFileSize", pFile->zPath);
         1840  +    pFile->lastErrno = lastErrno;
         1841  +    return winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
         1842  +             "winFileSize", pFile->zPath);
  1321   1843     }
  1322   1844     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  1323   1845     return SQLITE_OK;
  1324   1846   }
  1325   1847   
  1326   1848   /*
  1327   1849   ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
................................................................................
  1329   1851   #ifndef LOCKFILE_FAIL_IMMEDIATELY
  1330   1852   # define LOCKFILE_FAIL_IMMEDIATELY 1
  1331   1853   #endif
  1332   1854   
  1333   1855   /*
  1334   1856   ** Acquire a reader lock.
  1335   1857   ** Different API routines are called depending on whether or not this
  1336         -** is Win95 or WinNT.
         1858  +** is Win9x or WinNT.
  1337   1859   */
  1338   1860   static int getReadLock(winFile *pFile){
  1339   1861     int res;
  1340   1862     if( isNT() ){
  1341   1863       OVERLAPPED ovlp;
  1342   1864       ovlp.Offset = SHARED_FIRST;
  1343   1865       ovlp.OffsetHigh = 0;
  1344   1866       ovlp.hEvent = 0;
  1345         -    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
  1346         -                     0, SHARED_SIZE, 0, &ovlp);
         1867  +    res = osLockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
         1868  +                       0, SHARED_SIZE, 0, &ovlp);
  1347   1869   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  1348   1870   */
  1349   1871   #if SQLITE_OS_WINCE==0
  1350   1872     }else{
  1351   1873       int lk;
  1352   1874       sqlite3_randomness(sizeof(lk), &lk);
  1353   1875       pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  1354         -    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
         1876  +    res = osLockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  1355   1877   #endif
  1356   1878     }
  1357   1879     if( res == 0 ){
  1358         -    pFile->lastErrno = GetLastError();
         1880  +    pFile->lastErrno = osGetLastError();
  1359   1881       /* No need to log a failure to lock */
  1360   1882     }
  1361   1883     return res;
  1362   1884   }
  1363   1885   
  1364   1886   /*
  1365   1887   ** Undo a readlock
  1366   1888   */
  1367   1889   static int unlockReadLock(winFile *pFile){
  1368   1890     int res;
         1891  +  DWORD lastErrno;
  1369   1892     if( isNT() ){
  1370         -    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
         1893  +    res = osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  1371   1894   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  1372   1895   */
  1373   1896   #if SQLITE_OS_WINCE==0
  1374   1897     }else{
  1375         -    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
         1898  +    res = osUnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
  1376   1899   #endif
  1377   1900     }
  1378         -  if( res==0 && GetLastError()!=ERROR_NOT_LOCKED ){
  1379         -    pFile->lastErrno = GetLastError();
  1380         -    winLogError(SQLITE_IOERR_UNLOCK, "unlockReadLock", pFile->zPath);
         1901  +  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
         1902  +    pFile->lastErrno = lastErrno;
         1903  +    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
         1904  +             "unlockReadLock", pFile->zPath);
  1381   1905     }
  1382   1906     return res;
  1383   1907   }
  1384   1908   
  1385   1909   /*
  1386   1910   ** Lock the file with the lock specified by parameter locktype - one
  1387   1911   ** of the following:
................................................................................
  1406   1930   ** This routine will only increase a lock.  The winUnlock() routine
  1407   1931   ** erases all locks at once and returns us immediately to locking level 0.
  1408   1932   ** It is not possible to lower the locking level one step at a time.  You
  1409   1933   ** must go straight to locking level 0.
  1410   1934   */
  1411   1935   static int winLock(sqlite3_file *id, int locktype){
  1412   1936     int rc = SQLITE_OK;    /* Return code from subroutines */
  1413         -  int res = 1;           /* Result of a windows lock call */
         1937  +  int res = 1;           /* Result of a Windows lock call */
  1414   1938     int newLocktype;       /* Set pFile->locktype to this value before exiting */
  1415   1939     int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  1416   1940     winFile *pFile = (winFile*)id;
  1417         -  DWORD error = NO_ERROR;
         1941  +  DWORD lastErrno = NO_ERROR;
  1418   1942   
  1419   1943     assert( id!=0 );
  1420   1944     OSTRACE(("LOCK %d %d was %d(%d)\n",
  1421   1945              pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
  1422   1946   
  1423   1947     /* If there is already a lock of this type or more restrictive on the
  1424   1948     ** OsFile, do nothing. Don't use the end_lock: exit path, as
................................................................................
  1440   1964     */
  1441   1965     newLocktype = pFile->locktype;
  1442   1966     if(   (pFile->locktype==NO_LOCK)
  1443   1967        || (   (locktype==EXCLUSIVE_LOCK)
  1444   1968            && (pFile->locktype==RESERVED_LOCK))
  1445   1969     ){
  1446   1970       int cnt = 3;
  1447         -    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
  1448         -      /* Try 3 times to get the pending lock.  The pending lock might be
  1449         -      ** held by another reader process who will release it momentarily.
         1971  +    while( cnt-->0 && (res = osLockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
         1972  +      /* Try 3 times to get the pending lock.  This is needed to work
         1973  +      ** around problems caused by indexing and/or anti-virus software on
         1974  +      ** Windows systems.
         1975  +      ** If you are using this code as a model for alternative VFSes, do not
         1976  +      ** copy this retry logic.  It is a hack intended for Windows only.
  1450   1977         */
  1451   1978         OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
  1452         -      Sleep(1);
         1979  +      if( cnt ) osSleep(1);
  1453   1980       }
  1454   1981       gotPendingLock = res;
  1455   1982       if( !res ){
  1456         -      error = GetLastError();
         1983  +      lastErrno = osGetLastError();
  1457   1984       }
  1458   1985     }
  1459   1986   
  1460   1987     /* Acquire a shared lock
  1461   1988     */
  1462   1989     if( locktype==SHARED_LOCK && res ){
  1463   1990       assert( pFile->locktype==NO_LOCK );
  1464   1991       res = getReadLock(pFile);
  1465   1992       if( res ){
  1466   1993         newLocktype = SHARED_LOCK;
  1467   1994       }else{
  1468         -      error = GetLastError();
         1995  +      lastErrno = osGetLastError();
  1469   1996       }
  1470   1997     }
  1471   1998   
  1472   1999     /* Acquire a RESERVED lock
  1473   2000     */
  1474   2001     if( locktype==RESERVED_LOCK && res ){
  1475   2002       assert( pFile->locktype==SHARED_LOCK );
  1476         -    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
         2003  +    res = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  1477   2004       if( res ){
  1478   2005         newLocktype = RESERVED_LOCK;
  1479   2006       }else{
  1480         -      error = GetLastError();
         2007  +      lastErrno = osGetLastError();
  1481   2008       }
  1482   2009     }
  1483   2010   
  1484   2011     /* Acquire a PENDING lock
  1485   2012     */
  1486   2013     if( locktype==EXCLUSIVE_LOCK && res ){
  1487   2014       newLocktype = PENDING_LOCK;
................................................................................
  1490   2017   
  1491   2018     /* Acquire an EXCLUSIVE lock
  1492   2019     */
  1493   2020     if( locktype==EXCLUSIVE_LOCK && res ){
  1494   2021       assert( pFile->locktype>=SHARED_LOCK );
  1495   2022       res = unlockReadLock(pFile);
  1496   2023       OSTRACE(("unreadlock = %d\n", res));
  1497         -    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
         2024  +    res = osLockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  1498   2025       if( res ){
  1499   2026         newLocktype = EXCLUSIVE_LOCK;
  1500   2027       }else{
  1501         -      error = GetLastError();
  1502         -      OSTRACE(("error-code = %d\n", error));
         2028  +      lastErrno = osGetLastError();
         2029  +      OSTRACE(("error-code = %d\n", lastErrno));
  1503   2030         getReadLock(pFile);
  1504   2031       }
  1505   2032     }
  1506   2033   
  1507   2034     /* If we are holding a PENDING lock that ought to be released, then
  1508   2035     ** release it now.
  1509   2036     */
  1510   2037     if( gotPendingLock && locktype==SHARED_LOCK ){
  1511         -    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
         2038  +    osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  1512   2039     }
  1513   2040   
  1514   2041     /* Update the state of the lock has held in the file descriptor then
  1515   2042     ** return the appropriate result code.
  1516   2043     */
  1517   2044     if( res ){
  1518   2045       rc = SQLITE_OK;
  1519   2046     }else{
  1520   2047       OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
  1521   2048              locktype, newLocktype));
  1522         -    pFile->lastErrno = error;
         2049  +    pFile->lastErrno = lastErrno;
  1523   2050       rc = SQLITE_BUSY;
  1524   2051     }
  1525   2052     pFile->locktype = (u8)newLocktype;
  1526   2053     return rc;
  1527   2054   }
  1528   2055   
  1529   2056   /*
................................................................................
  1538   2065     SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  1539   2066   
  1540   2067     assert( id!=0 );
  1541   2068     if( pFile->locktype>=RESERVED_LOCK ){
  1542   2069       rc = 1;
  1543   2070       OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
  1544   2071     }else{
  1545         -    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
         2072  +    rc = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  1546   2073       if( rc ){
  1547         -      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
         2074  +      osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  1548   2075       }
  1549   2076       rc = !rc;
  1550   2077       OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
  1551   2078     }
  1552   2079     *pResOut = rc;
  1553   2080     return SQLITE_OK;
  1554   2081   }
................................................................................
  1570   2097     int rc = SQLITE_OK;
  1571   2098     assert( pFile!=0 );
  1572   2099     assert( locktype<=SHARED_LOCK );
  1573   2100     OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
  1574   2101             pFile->locktype, pFile->sharedLockByte));
  1575   2102     type = pFile->locktype;
  1576   2103     if( type>=EXCLUSIVE_LOCK ){
  1577         -    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
         2104  +    osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  1578   2105       if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
  1579   2106         /* This should never happen.  We should always be able to
  1580   2107         ** reacquire the read lock */
  1581         -      rc = winLogError(SQLITE_IOERR_UNLOCK, "winUnlock", pFile->zPath);
         2108  +      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
         2109  +               "winUnlock", pFile->zPath);
  1582   2110       }
  1583   2111     }
  1584   2112     if( type>=RESERVED_LOCK ){
  1585         -    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
         2113  +    osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
  1586   2114     }
  1587   2115     if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  1588   2116       unlockReadLock(pFile);
  1589   2117     }
  1590   2118     if( type>=PENDING_LOCK ){
  1591         -    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
         2119  +    osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  1592   2120     }
  1593   2121     pFile->locktype = (u8)locktype;
  1594   2122     return rc;
  1595   2123   }
         2124  +
         2125  +/*
         2126  +** If *pArg is inititially negative then this is a query.  Set *pArg to
         2127  +** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
         2128  +**
         2129  +** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
         2130  +*/
         2131  +static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
         2132  +  if( *pArg<0 ){
         2133  +    *pArg = (pFile->ctrlFlags & mask)!=0;
         2134  +  }else if( (*pArg)==0 ){
         2135  +    pFile->ctrlFlags &= ~mask;
         2136  +  }else{
         2137  +    pFile->ctrlFlags |= mask;
         2138  +  }
         2139  +}
  1596   2140   
  1597   2141   /*
  1598   2142   ** Control and query of the open file handle.
  1599   2143   */
  1600   2144   static int winFileControl(sqlite3_file *id, int op, void *pArg){
  1601   2145     winFile *pFile = (winFile*)id;
  1602   2146     switch( op ){
................................................................................
  1625   2169             }
  1626   2170           }
  1627   2171           return rc;
  1628   2172         }
  1629   2173         return SQLITE_OK;
  1630   2174       }
  1631   2175       case SQLITE_FCNTL_PERSIST_WAL: {
  1632         -      int bPersist = *(int*)pArg;
  1633         -      if( bPersist<0 ){
  1634         -        *(int*)pArg = pFile->bPersistWal;
  1635         -      }else{
  1636         -        pFile->bPersistWal = bPersist!=0;
  1637         -      }
         2176  +      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
         2177  +      return SQLITE_OK;
         2178  +    }
         2179  +    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
         2180  +      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  1638   2181         return SQLITE_OK;
  1639   2182       }
  1640         -    case SQLITE_FCNTL_SYNC_OMITTED: {
         2183  +    case SQLITE_FCNTL_VFSNAME: {
         2184  +      *(char**)pArg = sqlite3_mprintf("win32");
  1641   2185         return SQLITE_OK;
  1642   2186       }
  1643   2187       case SQLITE_FCNTL_WIN32_AV_RETRY: {
  1644   2188         int *a = (int*)pArg;
  1645   2189         if( a[0]>0 ){
  1646   2190           win32IoerrRetry = a[0];
  1647   2191         }else{
................................................................................
  1665   2209   **
  1666   2210   ** SQLite code assumes this function cannot fail. It also assumes that
  1667   2211   ** if two files are created in the same file-system directory (i.e.
  1668   2212   ** a database and its journal file) that the sector size will be the
  1669   2213   ** same for both.
  1670   2214   */
  1671   2215   static int winSectorSize(sqlite3_file *id){
  1672         -  assert( id!=0 );
  1673         -  return (int)(((winFile*)id)->sectorSize);
         2216  +  (void)id;
         2217  +  return SQLITE_DEFAULT_SECTOR_SIZE;
  1674   2218   }
  1675   2219   
  1676   2220   /*
  1677   2221   ** Return a vector of device characteristics.
  1678   2222   */
  1679   2223   static int winDeviceCharacteristics(sqlite3_file *id){
  1680         -  UNUSED_PARAMETER(id);
  1681         -  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
         2224  +  winFile *p = (winFile*)id;
         2225  +  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
         2226  +         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  1682   2227   }
  1683   2228   
  1684   2229   #ifndef SQLITE_OMIT_WAL
  1685   2230   
  1686   2231   /* 
  1687   2232   ** Windows will only let you create file view mappings
  1688   2233   ** on allocation size granularity boundaries.
................................................................................
  1821   2366     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  1822   2367   
  1823   2368     memset(&ovlp, 0, sizeof(OVERLAPPED));
  1824   2369     ovlp.Offset = ofst;
  1825   2370   
  1826   2371     /* Release/Acquire the system-level lock */
  1827   2372     if( lockType==_SHM_UNLCK ){
  1828         -    rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
         2373  +    rc = osUnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
  1829   2374     }else{
  1830         -    rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
         2375  +    rc = osLockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
  1831   2376     }
  1832   2377     
  1833   2378     if( rc!= 0 ){
  1834   2379       rc = SQLITE_OK;
  1835   2380     }else{
  1836         -    pFile->lastErrno =  GetLastError();
         2381  +    pFile->lastErrno =  osGetLastError();
  1837   2382       rc = SQLITE_BUSY;
  1838   2383     }
  1839   2384   
  1840   2385     OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n", 
  1841   2386              pFile->hFile.h,
  1842   2387              rc==SQLITE_OK ? "ok" : "failed",
  1843   2388              lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
................................................................................
  1863   2408     assert( winShmMutexHeld() );
  1864   2409     pp = &winShmNodeList;
  1865   2410     while( (p = *pp)!=0 ){
  1866   2411       if( p->nRef==0 ){
  1867   2412         int i;
  1868   2413         if( p->mutex ) sqlite3_mutex_free(p->mutex);
  1869   2414         for(i=0; i<p->nRegion; i++){
  1870         -        bRc = UnmapViewOfFile(p->aRegion[i].pMap);
         2415  +        bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  1871   2416           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
  1872         -                 (int)GetCurrentProcessId(), i,
         2417  +                 (int)osGetCurrentProcessId(), i,
  1873   2418                    bRc ? "ok" : "failed"));
  1874         -        bRc = CloseHandle(p->aRegion[i].hMap);
         2419  +        bRc = osCloseHandle(p->aRegion[i].hMap);
  1875   2420           OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
  1876         -                 (int)GetCurrentProcessId(), i,
         2421  +                 (int)osGetCurrentProcessId(), i,
  1877   2422                    bRc ? "ok" : "failed"));
  1878   2423         }
  1879   2424         if( p->hFile.h != INVALID_HANDLE_VALUE ){
  1880   2425           SimulateIOErrorBenign(1);
  1881   2426           winClose((sqlite3_file *)&p->hFile);
  1882   2427           SimulateIOErrorBenign(0);
  1883   2428         }
................................................................................
  1911   2456   
  1912   2457     assert( pDbFd->pShm==0 );    /* Not previously opened */
  1913   2458   
  1914   2459     /* Allocate space for the new sqlite3_shm object.  Also speculatively
  1915   2460     ** allocate space for a new winShmNode and filename.
  1916   2461     */
  1917   2462     p = sqlite3_malloc( sizeof(*p) );
  1918         -  if( p==0 ) return SQLITE_NOMEM;
         2463  +  if( p==0 ) return SQLITE_IOERR_NOMEM;
  1919   2464     memset(p, 0, sizeof(*p));
  1920   2465     nName = sqlite3Strlen30(pDbFd->zPath);
  1921         -  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
         2466  +  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 16 );
  1922   2467     if( pNew==0 ){
  1923   2468       sqlite3_free(p);
  1924         -    return SQLITE_NOMEM;
         2469  +    return SQLITE_IOERR_NOMEM;
  1925   2470     }
  1926   2471     memset(pNew, 0, sizeof(*pNew));
  1927   2472     pNew->zFilename = (char*)&pNew[1];
  1928   2473     sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  1929   2474     sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
  1930   2475   
  1931   2476     /* Look to see if there is an existing winShmNode that can be used.
................................................................................
  1945   2490       pNew = 0;
  1946   2491       ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  1947   2492       pShmNode->pNext = winShmNodeList;
  1948   2493       winShmNodeList = pShmNode;
  1949   2494   
  1950   2495       pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  1951   2496       if( pShmNode->mutex==0 ){
  1952         -      rc = SQLITE_NOMEM;
         2497  +      rc = SQLITE_IOERR_NOMEM;
  1953   2498         goto shm_open_err;
  1954   2499       }
  1955   2500   
  1956   2501       rc = winOpen(pDbFd->pVfs,
  1957   2502                    pShmNode->zFilename,             /* Name of the file (UTF-8) */
  1958   2503                    (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
  1959   2504                    SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
................................................................................
  1965   2510   
  1966   2511       /* Check to see if another process is holding the dead-man switch.
  1967   2512       ** If not, truncate the file to zero length. 
  1968   2513       */
  1969   2514       if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  1970   2515         rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  1971   2516         if( rc!=SQLITE_OK ){
  1972         -        rc = winLogError(SQLITE_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath);
         2517  +        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
         2518  +                 "winOpenShm", pDbFd->zPath);
  1973   2519         }
  1974   2520       }
  1975   2521       if( rc==SQLITE_OK ){
  1976   2522         winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  1977   2523         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  1978   2524       }
  1979   2525       if( rc ) goto shm_open_err;
................................................................................
  2150   2696           assert( (p->sharedMask & mask)==0 );
  2151   2697           p->exclMask |= mask;
  2152   2698         }
  2153   2699       }
  2154   2700     }
  2155   2701     sqlite3_mutex_leave(pShmNode->mutex);
  2156   2702     OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
  2157         -           p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
         2703  +           p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
  2158   2704              rc ? "failed" : "ok"));
  2159   2705     return rc;
  2160   2706   }
  2161   2707   
  2162   2708   /*
  2163   2709   ** Implement a memory barrier or memory fence on shared memory.  
  2164   2710   **
................................................................................
  2224   2770   
  2225   2771       /* The requested region is not mapped into this processes address space.
  2226   2772       ** Check to see if it has been allocated (i.e. if the wal-index file is
  2227   2773       ** large enough to contain the requested region).
  2228   2774       */
  2229   2775       rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  2230   2776       if( rc!=SQLITE_OK ){
  2231         -      rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath);
         2777  +      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
         2778  +               "winShmMap1", pDbFd->zPath);
  2232   2779         goto shmpage_out;
  2233   2780       }
  2234   2781   
  2235   2782       if( sz<nByte ){
  2236   2783         /* The requested memory region does not exist. If isWrite is set to
  2237   2784         ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  2238   2785         **
  2239   2786         ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  2240   2787         ** the requested memory region.
  2241   2788         */
  2242   2789         if( !isWrite ) goto shmpage_out;
  2243   2790         rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  2244   2791         if( rc!=SQLITE_OK ){
  2245         -        rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath);
         2792  +        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
         2793  +                 "winShmMap2", pDbFd->zPath);
  2246   2794           goto shmpage_out;
  2247   2795         }
  2248   2796       }
  2249   2797   
  2250   2798       /* Map the requested memory region into this processes address space. */
  2251   2799       apNew = (struct ShmRegion *)sqlite3_realloc(
  2252   2800           pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
................................................................................
  2257   2805       }
  2258   2806       pShmNode->aRegion = apNew;
  2259   2807   
  2260   2808       while( pShmNode->nRegion<=iRegion ){
  2261   2809         HANDLE hMap;                /* file-mapping handle */
  2262   2810         void *pMap = 0;             /* Mapped memory region */
  2263   2811        
  2264         -      hMap = CreateFileMapping(pShmNode->hFile.h, 
         2812  +      hMap = osCreateFileMapping(pShmNode->hFile.h, 
  2265   2813             NULL, PAGE_READWRITE, 0, nByte, NULL
  2266   2814         );
  2267   2815         OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
  2268         -               (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
         2816  +               (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  2269   2817                  hMap ? "ok" : "failed"));
  2270   2818         if( hMap ){
  2271   2819           int iOffset = pShmNode->nRegion*szRegion;
  2272   2820           int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  2273         -        pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
         2821  +        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  2274   2822               0, iOffset - iOffsetShift, szRegion + iOffsetShift
  2275   2823           );
  2276   2824           OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
  2277         -                 (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
  2278         -                 pMap ? "ok" : "failed"));
         2825  +                 (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
         2826  +                 szRegion, pMap ? "ok" : "failed"));
  2279   2827         }
  2280   2828         if( !pMap ){
  2281         -        pShmNode->lastErrno = GetLastError();
  2282         -        rc = winLogError(SQLITE_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath);
  2283         -        if( hMap ) CloseHandle(hMap);
         2829  +        pShmNode->lastErrno = osGetLastError();
         2830  +        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
         2831  +                 "winShmMap3", pDbFd->zPath);
         2832  +        if( hMap ) osCloseHandle(hMap);
  2284   2833           goto shmpage_out;
  2285   2834         }
  2286   2835   
  2287   2836         pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  2288   2837         pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  2289   2838         pShmNode->nRegion++;
  2290   2839       }
................................................................................
  2387   2936     SimulateIOError( return SQLITE_IOERR );
  2388   2937   
  2389   2938     if( sqlite3_temp_directory ){
  2390   2939       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
  2391   2940     }else if( isNT() ){
  2392   2941       char *zMulti;
  2393   2942       WCHAR zWidePath[MAX_PATH];
  2394         -    GetTempPathW(MAX_PATH-30, zWidePath);
         2943  +    osGetTempPathW(MAX_PATH-30, zWidePath);
  2395   2944       zMulti = unicodeToUtf8(zWidePath);
  2396   2945       if( zMulti ){
  2397   2946         sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
  2398         -      free(zMulti);
         2947  +      sqlite3_free(zMulti);
  2399   2948       }else{
  2400         -      return SQLITE_NOMEM;
         2949  +      return SQLITE_IOERR_NOMEM;
  2401   2950       }
  2402   2951   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  2403         -** Since the ASCII version of these Windows API do not exist for WINCE,
         2952  +** Since the ANSI version of these Windows API do not exist for WINCE,
  2404   2953   ** it's important to not reference them for WINCE builds.
  2405   2954   */
  2406   2955   #if SQLITE_OS_WINCE==0
  2407   2956     }else{
  2408   2957       char *zUtf8;
  2409   2958       char zMbcsPath[MAX_PATH];
  2410         -    GetTempPathA(MAX_PATH-30, zMbcsPath);
         2959  +    osGetTempPathA(MAX_PATH-30, zMbcsPath);
  2411   2960       zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  2412   2961       if( zUtf8 ){
  2413   2962         sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
  2414         -      free(zUtf8);
         2963  +      sqlite3_free(zUtf8);
  2415   2964       }else{
  2416         -      return SQLITE_NOMEM;
         2965  +      return SQLITE_IOERR_NOMEM;
  2417   2966       }
  2418   2967   #endif
  2419   2968     }
  2420   2969   
  2421   2970     /* Check that the output buffer is large enough for the temporary file 
  2422   2971     ** name. If it is not, return SQLITE_ERROR.
  2423   2972     */
................................................................................
  2448   2997     sqlite3_vfs *pVfs,        /* Not used */
  2449   2998     const char *zName,        /* Name of the file (UTF-8) */
  2450   2999     sqlite3_file *id,         /* Write the SQLite file handle here */
  2451   3000     int flags,                /* Open mode flags */
  2452   3001     int *pOutFlags            /* Status return flags */
  2453   3002   ){
  2454   3003     HANDLE h;
         3004  +  DWORD lastErrno;
  2455   3005     DWORD dwDesiredAccess;
  2456   3006     DWORD dwShareMode;
  2457   3007     DWORD dwCreationDisposition;
  2458   3008     DWORD dwFlagsAndAttributes = 0;
  2459   3009   #if SQLITE_OS_WINCE
  2460   3010     int isTemp = 0;
  2461   3011   #endif
................................................................................
  2532   3082       }
  2533   3083       zUtf8Name = zTmpname;
  2534   3084     }
  2535   3085   
  2536   3086     /* Convert the filename to the system encoding. */
  2537   3087     zConverted = convertUtf8Filename(zUtf8Name);
  2538   3088     if( zConverted==0 ){
  2539         -    return SQLITE_NOMEM;
         3089  +    return SQLITE_IOERR_NOMEM;
  2540   3090     }
  2541   3091   
  2542   3092     if( isReadWrite ){
  2543   3093       dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  2544   3094     }else{
  2545   3095       dwDesiredAccess = GENERIC_READ;
  2546   3096     }
................................................................................
  2578   3128     /* Reports from the internet are that performance is always
  2579   3129     ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
  2580   3130   #if SQLITE_OS_WINCE
  2581   3131     dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  2582   3132   #endif
  2583   3133   
  2584   3134     if( isNT() ){
  2585         -    while( (h = CreateFileW((WCHAR*)zConverted,
  2586         -                            dwDesiredAccess,
  2587         -                            dwShareMode, NULL,
  2588         -                            dwCreationDisposition,
  2589         -                            dwFlagsAndAttributes,
  2590         -                            NULL))==INVALID_HANDLE_VALUE &&
  2591         -                            retryIoerr(&cnt) ){}
         3135  +    while( (h = osCreateFileW((LPCWSTR)zConverted,
         3136  +                              dwDesiredAccess,
         3137  +                              dwShareMode, NULL,
         3138  +                              dwCreationDisposition,
         3139  +                              dwFlagsAndAttributes,
         3140  +                              NULL))==INVALID_HANDLE_VALUE &&
         3141  +                              retryIoerr(&cnt, &lastErrno) ){}
  2592   3142   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  2593         -** Since the ASCII version of these Windows API do not exist for WINCE,
         3143  +** Since the ANSI version of these Windows API do not exist for WINCE,
  2594   3144   ** it's important to not reference them for WINCE builds.
  2595   3145   */
  2596   3146   #if SQLITE_OS_WINCE==0
  2597   3147     }else{
  2598         -    while( (h = CreateFileA((char*)zConverted,
  2599         -                            dwDesiredAccess,
  2600         -                            dwShareMode, NULL,
  2601         -                            dwCreationDisposition,
  2602         -                            dwFlagsAndAttributes,
  2603         -                            NULL))==INVALID_HANDLE_VALUE &&
  2604         -                            retryIoerr(&cnt) ){}
         3148  +    while( (h = osCreateFileA((LPCSTR)zConverted,
         3149  +                              dwDesiredAccess,
         3150  +                              dwShareMode, NULL,
         3151  +                              dwCreationDisposition,
         3152  +                              dwFlagsAndAttributes,
         3153  +                              NULL))==INVALID_HANDLE_VALUE &&
         3154  +                              retryIoerr(&cnt, &lastErrno) ){}
  2605   3155   #endif
  2606   3156     }
  2607   3157   
  2608   3158     logIoerr(cnt);
  2609   3159   
  2610   3160     OSTRACE(("OPEN %d %s 0x%lx %s\n", 
  2611   3161              h, zName, dwDesiredAccess, 
  2612   3162              h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
  2613   3163   
  2614   3164     if( h==INVALID_HANDLE_VALUE ){
  2615         -    pFile->lastErrno = GetLastError();
  2616         -    winLogError(SQLITE_CANTOPEN, "winOpen", zUtf8Name);
  2617         -    free(zConverted);
         3165  +    pFile->lastErrno = lastErrno;
         3166  +    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
         3167  +    sqlite3_free(zConverted);
  2618   3168       if( isReadWrite && !isExclusive ){
  2619   3169         return winOpen(pVfs, zName, id, 
  2620   3170                ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
  2621   3171       }else{
  2622   3172         return SQLITE_CANTOPEN_BKPT;
  2623   3173       }
  2624   3174     }
................................................................................
  2634   3184     memset(pFile, 0, sizeof(*pFile));
  2635   3185     pFile->pMethod = &winIoMethod;
  2636   3186     pFile->h = h;
  2637   3187     pFile->lastErrno = NO_ERROR;
  2638   3188     pFile->pVfs = pVfs;
  2639   3189     pFile->pShm = 0;
  2640   3190     pFile->zPath = zName;
  2641         -  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
         3191  +  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
         3192  +    pFile->ctrlFlags |= WINFILE_PSOW;
         3193  +  }
  2642   3194   
  2643   3195   #if SQLITE_OS_WINCE
  2644   3196     if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  2645   3197          && !winceCreateLock(zName, pFile)
  2646   3198     ){
  2647         -    CloseHandle(h);
  2648         -    free(zConverted);
         3199  +    osCloseHandle(h);
         3200  +    sqlite3_free(zConverted);
  2649   3201       return SQLITE_CANTOPEN_BKPT;
  2650   3202     }
  2651   3203     if( isTemp ){
  2652   3204       pFile->zDeleteOnClose = zConverted;
  2653   3205     }else
  2654   3206   #endif
  2655   3207     {
  2656         -    free(zConverted);
         3208  +    sqlite3_free(zConverted);
  2657   3209     }
  2658   3210   
  2659   3211     OpenCounter(+1);
  2660   3212     return rc;
  2661   3213   }
  2662   3214   
  2663   3215   /*
  2664   3216   ** Delete the named file.
  2665   3217   **
  2666         -** Note that windows does not allow a file to be deleted if some other
         3218  +** Note that Windows does not allow a file to be deleted if some other
  2667   3219   ** process has it open.  Sometimes a virus scanner or indexing program
  2668   3220   ** will open a journal file shortly after it is created in order to do
  2669   3221   ** whatever it does.  While this other process is holding the
  2670   3222   ** file open, we will be unable to delete it.  To work around this
  2671   3223   ** problem, we delay 100 milliseconds and try to delete again.  Up
  2672   3224   ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  2673   3225   ** up and returning an error.
................................................................................
  2675   3227   static int winDelete(
  2676   3228     sqlite3_vfs *pVfs,          /* Not used on win32 */
  2677   3229     const char *zFilename,      /* Name of file to delete */
  2678   3230     int syncDir                 /* Not used on win32 */
  2679   3231   ){
  2680   3232     int cnt = 0;
  2681   3233     int rc;
         3234  +  DWORD lastErrno;
  2682   3235     void *zConverted;
  2683   3236     UNUSED_PARAMETER(pVfs);
  2684   3237     UNUSED_PARAMETER(syncDir);
  2685   3238   
  2686   3239     SimulateIOError(return SQLITE_IOERR_DELETE);
  2687   3240     zConverted = convertUtf8Filename(zFilename);
  2688   3241     if( zConverted==0 ){
  2689         -    return SQLITE_NOMEM;
         3242  +    return SQLITE_IOERR_NOMEM;
  2690   3243     }
  2691   3244     if( isNT() ){
  2692   3245       rc = 1;
  2693         -    while( GetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
  2694         -           (rc = DeleteFileW(zConverted))==0 && retryIoerr(&cnt) ){}
         3246  +    while( osGetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
         3247  +         (rc = osDeleteFileW(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
  2695   3248       rc = rc ? SQLITE_OK : SQLITE_ERROR;
  2696   3249   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  2697         -** Since the ASCII version of these Windows API do not exist for WINCE,
         3250  +** Since the ANSI version of these Windows API do not exist for WINCE,
  2698   3251   ** it's important to not reference them for WINCE builds.
  2699   3252   */
  2700   3253   #if SQLITE_OS_WINCE==0
  2701   3254     }else{
  2702   3255       rc = 1;
  2703         -    while( GetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
  2704         -           (rc = DeleteFileA(zConverted))==0 && retryIoerr(&cnt) ){}
         3256  +    while( osGetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
         3257  +         (rc = osDeleteFileA(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
  2705   3258       rc = rc ? SQLITE_OK : SQLITE_ERROR;
  2706   3259   #endif
  2707   3260     }
  2708   3261     if( rc ){
  2709         -    rc = winLogError(SQLITE_IOERR_DELETE, "winDelete", zFilename);
         3262  +    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
         3263  +             "winDelete", zFilename);
  2710   3264     }else{
  2711   3265       logIoerr(cnt);
  2712   3266     }
  2713         -  free(zConverted);
         3267  +  sqlite3_free(zConverted);
  2714   3268     OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
  2715   3269     return rc;
  2716   3270   }
  2717   3271   
  2718   3272   /*
  2719   3273   ** Check the existance and status of a file.
  2720   3274   */
................................................................................
  2722   3276     sqlite3_vfs *pVfs,         /* Not used on win32 */
  2723   3277     const char *zFilename,     /* Name of file to check */
  2724   3278     int flags,                 /* Type of test to make on this file */
  2725   3279     int *pResOut               /* OUT: Result */
  2726   3280   ){
  2727   3281     DWORD attr;
  2728   3282     int rc = 0;
         3283  +  DWORD lastErrno;
  2729   3284     void *zConverted;
  2730   3285     UNUSED_PARAMETER(pVfs);
  2731   3286   
  2732   3287     SimulateIOError( return SQLITE_IOERR_ACCESS; );
  2733   3288     zConverted = convertUtf8Filename(zFilename);
  2734   3289     if( zConverted==0 ){
  2735         -    return SQLITE_NOMEM;
         3290  +    return SQLITE_IOERR_NOMEM;
  2736   3291     }
  2737   3292     if( isNT() ){
  2738   3293       int cnt = 0;
  2739   3294       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  2740   3295       memset(&sAttrData, 0, sizeof(sAttrData));
  2741         -    while( !(rc = GetFileAttributesExW((WCHAR*)zConverted,
         3296  +    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  2742   3297                                GetFileExInfoStandard, 
  2743         -                             &sAttrData)) && retryIoerr(&cnt) ){}
         3298  +                             &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
  2744   3299       if( rc ){
  2745   3300         /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  2746   3301         ** as if it does not exist.
  2747   3302         */
  2748   3303         if(    flags==SQLITE_ACCESS_EXISTS
  2749   3304             && sAttrData.nFileSizeHigh==0 
  2750   3305             && sAttrData.nFileSizeLow==0 ){
  2751   3306           attr = INVALID_FILE_ATTRIBUTES;
  2752   3307         }else{
  2753   3308           attr = sAttrData.dwFileAttributes;
  2754   3309         }
  2755   3310       }else{
  2756   3311         logIoerr(cnt);
  2757         -      if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
  2758         -        winLogError(SQLITE_IOERR_ACCESS, "winAccess", zFilename);
  2759         -        free(zConverted);
         3312  +      if( lastErrno!=ERROR_FILE_NOT_FOUND ){
         3313  +        winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
         3314  +        sqlite3_free(zConverted);
  2760   3315           return SQLITE_IOERR_ACCESS;
  2761   3316         }else{
  2762   3317           attr = INVALID_FILE_ATTRIBUTES;
  2763   3318         }
  2764   3319       }
  2765   3320   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  2766         -** Since the ASCII version of these Windows API do not exist for WINCE,
         3321  +** Since the ANSI version of these Windows API do not exist for WINCE,
  2767   3322   ** it's important to not reference them for WINCE builds.
  2768   3323   */
  2769   3324   #if SQLITE_OS_WINCE==0
  2770   3325     }else{
  2771         -    attr = GetFileAttributesA((char*)zConverted);
         3326  +    attr = osGetFileAttributesA((char*)zConverted);
  2772   3327   #endif
  2773   3328     }
  2774         -  free(zConverted);
         3329  +  sqlite3_free(zConverted);
  2775   3330     switch( flags ){
  2776   3331       case SQLITE_ACCESS_READ:
  2777   3332       case SQLITE_ACCESS_EXISTS:
  2778   3333         rc = attr!=INVALID_FILE_ATTRIBUTES;
  2779   3334         break;
  2780   3335       case SQLITE_ACCESS_READWRITE:
  2781   3336         rc = attr!=INVALID_FILE_ATTRIBUTES &&
................................................................................
  2832   3387     ** using the io-error infrastructure to test that SQLite handles this
  2833   3388     ** function failing. This function could fail if, for example, the
  2834   3389     ** current working directory has been unlinked.
  2835   3390     */
  2836   3391     SimulateIOError( return SQLITE_ERROR );
  2837   3392     UNUSED_PARAMETER(nFull);
  2838   3393     zConverted = convertUtf8Filename(zRelative);
         3394  +  if( zConverted==0 ){
         3395  +    return SQLITE_IOERR_NOMEM;
         3396  +  }
  2839   3397     if( isNT() ){
  2840         -    WCHAR *zTemp;
  2841         -    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
  2842         -    zTemp = malloc( nByte*sizeof(zTemp[0]) );
         3398  +    LPWSTR zTemp;
         3399  +    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;
         3400  +    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
  2843   3401       if( zTemp==0 ){
  2844         -      free(zConverted);
  2845         -      return SQLITE_NOMEM;
         3402  +      sqlite3_free(zConverted);
         3403  +      return SQLITE_IOERR_NOMEM;
  2846   3404       }
  2847         -    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
  2848         -    free(zConverted);
         3405  +    osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
         3406  +    sqlite3_free(zConverted);
  2849   3407       zOut = unicodeToUtf8(zTemp);
  2850         -    free(zTemp);
         3408  +    sqlite3_free(zTemp);
  2851   3409   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  2852         -** Since the ASCII version of these Windows API do not exist for WINCE,
         3410  +** Since the ANSI version of these Windows API do not exist for WINCE,
  2853   3411   ** it's important to not reference them for WINCE builds.
  2854   3412   */
  2855   3413   #if SQLITE_OS_WINCE==0
  2856   3414     }else{
  2857   3415       char *zTemp;
  2858         -    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
  2859         -    zTemp = malloc( nByte*sizeof(zTemp[0]) );
         3416  +    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
         3417  +    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
  2860   3418       if( zTemp==0 ){
  2861         -      free(zConverted);
  2862         -      return SQLITE_NOMEM;
         3419  +      sqlite3_free(zConverted);
         3420  +      return SQLITE_IOERR_NOMEM;
  2863   3421       }
  2864         -    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  2865         -    free(zConverted);
         3422  +    osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
         3423  +    sqlite3_free(zConverted);
  2866   3424       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  2867         -    free(zTemp);
         3425  +    sqlite3_free(zTemp);
  2868   3426   #endif
  2869   3427     }
  2870   3428     if( zOut ){
  2871   3429       sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
  2872         -    free(zOut);
         3430  +    sqlite3_free(zOut);
  2873   3431       return SQLITE_OK;
  2874   3432     }else{
  2875         -    return SQLITE_NOMEM;
         3433  +    return SQLITE_IOERR_NOMEM;
  2876   3434     }
  2877   3435   #endif
  2878   3436   }
  2879   3437   
  2880         -/*
  2881         -** Get the sector size of the device used to store
  2882         -** file.
  2883         -*/
  2884         -static int getSectorSize(
  2885         -    sqlite3_vfs *pVfs,
  2886         -    const char *zRelative     /* UTF-8 file name */
  2887         -){
  2888         -  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
  2889         -  /* GetDiskFreeSpace is not supported under WINCE */
  2890         -#if SQLITE_OS_WINCE
  2891         -  UNUSED_PARAMETER(pVfs);
  2892         -  UNUSED_PARAMETER(zRelative);
  2893         -#else
  2894         -  char zFullpath[MAX_PATH+1];
  2895         -  int rc;
  2896         -  DWORD dwRet = 0;
  2897         -  DWORD dwDummy;
  2898         -
  2899         -  /*
  2900         -  ** We need to get the full path name of the file
  2901         -  ** to get the drive letter to look up the sector
  2902         -  ** size.
  2903         -  */
  2904         -  SimulateIOErrorBenign(1);
  2905         -  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
  2906         -  SimulateIOErrorBenign(0);
  2907         -  if( rc == SQLITE_OK )
  2908         -  {
  2909         -    void *zConverted = convertUtf8Filename(zFullpath);
  2910         -    if( zConverted ){
  2911         -      if( isNT() ){
  2912         -        /* trim path to just drive reference */
  2913         -        WCHAR *p = zConverted;
  2914         -        for(;*p;p++){
  2915         -          if( *p == '\\' ){
  2916         -            *p = '\0';
  2917         -            break;
  2918         -          }
  2919         -        }
  2920         -        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
  2921         -                                  &dwDummy,
  2922         -                                  &bytesPerSector,
  2923         -                                  &dwDummy,
  2924         -                                  &dwDummy);
  2925         -      }else{
  2926         -        /* trim path to just drive reference */
  2927         -        char *p = (char *)zConverted;
  2928         -        for(;*p;p++){
  2929         -          if( *p == '\\' ){
  2930         -            *p = '\0';
  2931         -            break;
  2932         -          }
  2933         -        }
  2934         -        dwRet = GetDiskFreeSpaceA((char*)zConverted,
  2935         -                                  &dwDummy,
  2936         -                                  &bytesPerSector,
  2937         -                                  &dwDummy,
  2938         -                                  &dwDummy);
  2939         -      }
  2940         -      free(zConverted);
  2941         -    }
  2942         -    if( !dwRet ){
  2943         -      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
  2944         -    }
  2945         -  }
  2946         -#endif
  2947         -  return (int) bytesPerSector; 
  2948         -}
  2949         -
  2950   3438   #ifndef SQLITE_OMIT_LOAD_EXTENSION
  2951   3439   /*
  2952   3440   ** Interfaces for opening a shared library, finding entry points
  2953   3441   ** within the shared library, and closing the shared library.
  2954   3442   */
  2955   3443   /*
  2956   3444   ** Interfaces for opening a shared library, finding entry points
................................................................................
  2960   3448     HANDLE h;
  2961   3449     void *zConverted = convertUtf8Filename(zFilename);
  2962   3450     UNUSED_PARAMETER(pVfs);
  2963   3451     if( zConverted==0 ){
  2964   3452       return 0;
  2965   3453     }
  2966   3454     if( isNT() ){
  2967         -    h = LoadLibraryW((WCHAR*)zConverted);
         3455  +    h = osLoadLibraryW((LPCWSTR)zConverted);
  2968   3456   /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
  2969         -** Since the ASCII version of these Windows API do not exist for WINCE,
         3457  +** Since the ANSI version of these Windows API do not exist for WINCE,
  2970   3458   ** it's important to not reference them for WINCE builds.
  2971   3459   */
  2972   3460   #if SQLITE_OS_WINCE==0
  2973   3461     }else{
  2974         -    h = LoadLibraryA((char*)zConverted);
         3462  +    h = osLoadLibraryA((char*)zConverted);
  2975   3463   #endif
  2976   3464     }
  2977         -  free(zConverted);
         3465  +  sqlite3_free(zConverted);
  2978   3466     return (void*)h;
  2979   3467   }
  2980   3468   static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  2981   3469     UNUSED_PARAMETER(pVfs);
  2982         -  getLastErrorMsg(nBuf, zBufOut);
         3470  +  getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  2983   3471   }
  2984   3472   static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
  2985   3473     UNUSED_PARAMETER(pVfs);
  2986         -#if SQLITE_OS_WINCE
  2987         -  /* The GetProcAddressA() routine is only available on wince. */
  2988         -  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
  2989         -#else
  2990         -  /* All other windows platforms expect GetProcAddress() to take
  2991         -  ** an Ansi string regardless of the _UNICODE setting */
  2992         -  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
  2993         -#endif
         3474  +  return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
  2994   3475   }
  2995   3476   static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  2996   3477     UNUSED_PARAMETER(pVfs);
  2997         -  FreeLibrary((HANDLE)pHandle);
         3478  +  osFreeLibrary((HANDLE)pHandle);
  2998   3479   }
  2999   3480   #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  3000   3481     #define winDlOpen  0
  3001   3482     #define winDlError 0
  3002   3483     #define winDlSym   0
  3003   3484     #define winDlClose 0
  3004   3485   #endif
................................................................................
  3012   3493     UNUSED_PARAMETER(pVfs);
  3013   3494   #if defined(SQLITE_TEST)
  3014   3495     n = nBuf;
  3015   3496     memset(zBuf, 0, nBuf);
  3016   3497   #else
  3017   3498     if( sizeof(SYSTEMTIME)<=nBuf-n ){
  3018   3499       SYSTEMTIME x;
  3019         -    GetSystemTime(&x);
         3500  +    osGetSystemTime(&x);
  3020   3501       memcpy(&zBuf[n], &x, sizeof(x));
  3021   3502       n += sizeof(x);
  3022   3503     }
  3023   3504     if( sizeof(DWORD)<=nBuf-n ){
  3024         -    DWORD pid = GetCurrentProcessId();
         3505  +    DWORD pid = osGetCurrentProcessId();
  3025   3506       memcpy(&zBuf[n], &pid, sizeof(pid));
  3026   3507       n += sizeof(pid);
  3027   3508     }
  3028   3509     if( sizeof(DWORD)<=nBuf-n ){
  3029         -    DWORD cnt = GetTickCount();
         3510  +    DWORD cnt = osGetTickCount();
  3030   3511       memcpy(&zBuf[n], &cnt, sizeof(cnt));
  3031   3512       n += sizeof(cnt);
  3032   3513     }
  3033   3514     if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  3034   3515       LARGE_INTEGER i;
  3035         -    QueryPerformanceCounter(&i);
         3516  +    osQueryPerformanceCounter(&i);
  3036   3517       memcpy(&zBuf[n], &i, sizeof(i));
  3037   3518       n += sizeof(i);
  3038   3519     }
  3039   3520   #endif
  3040   3521     return n;
  3041   3522   }
  3042   3523   
  3043   3524   
  3044   3525   /*
  3045   3526   ** Sleep for a little while.  Return the amount of time slept.
  3046   3527   */
  3047   3528   static int winSleep(sqlite3_vfs *pVfs, int microsec){
  3048         -  Sleep((microsec+999)/1000);
         3529  +  osSleep((microsec+999)/1000);
  3049   3530     UNUSED_PARAMETER(pVfs);
  3050   3531     return ((microsec+999)/1000)*1000;
  3051   3532   }
  3052   3533   
  3053   3534   /*
  3054   3535   ** The following variable, if set to a non-zero value, is interpreted as
  3055   3536   ** the number of seconds since 1970 and is used to set the result of
................................................................................
  3080   3561   #endif
  3081   3562     /* 2^32 - to avoid use of LL and warnings in gcc */
  3082   3563     static const sqlite3_int64 max32BitValue = 
  3083   3564         (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
  3084   3565   
  3085   3566   #if SQLITE_OS_WINCE
  3086   3567     SYSTEMTIME time;
  3087         -  GetSystemTime(&time);
         3568  +  osGetSystemTime(&time);
  3088   3569     /* if SystemTimeToFileTime() fails, it returns zero. */
  3089         -  if (!SystemTimeToFileTime(&time,&ft)){
         3570  +  if (!osSystemTimeToFileTime(&time,&ft)){
  3090   3571       return SQLITE_ERROR;
  3091   3572     }
  3092   3573   #else
  3093         -  GetSystemTimeAsFileTime( &ft );
         3574  +  osGetSystemTimeAsFileTime( &ft );
  3094   3575   #endif
  3095   3576   
  3096   3577     *piNow = winFiletimeEpoch +
  3097   3578               ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
  3098   3579                  (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  3099   3580   
  3100   3581   #ifdef SQLITE_TEST
................................................................................
  3119   3600       *prNow = i/86400000.0;
  3120   3601     }
  3121   3602     return rc;
  3122   3603   }
  3123   3604   
  3124   3605   /*
  3125   3606   ** The idea is that this function works like a combination of
  3126         -** GetLastError() and FormatMessage() on windows (or errno and
  3127         -** strerror_r() on unix). After an error is returned by an OS
         3607  +** GetLastError() and FormatMessage() on Windows (or errno and
         3608  +** strerror_r() on Unix). After an error is returned by an OS
  3128   3609   ** function, SQLite calls this function with zBuf pointing to
  3129   3610   ** a buffer of nBuf bytes. The OS layer should populate the
  3130   3611   ** buffer with a nul-terminated UTF-8 encoded error message
  3131   3612   ** describing the last IO error to have occurred within the calling
  3132   3613   ** thread.
  3133   3614   **
  3134   3615   ** If the error message is too large for the supplied buffer,
................................................................................
  3149   3630   **
  3150   3631   ** However if an error message is supplied, it will be incorporated
  3151   3632   ** by sqlite into the error message available to the user using
  3152   3633   ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  3153   3634   */
  3154   3635   static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  3155   3636     UNUSED_PARAMETER(pVfs);
  3156         -  return getLastErrorMsg(nBuf, zBuf);
         3637  +  return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
  3157   3638   }
  3158         -
  3159         -
  3160   3639   
  3161   3640   /*
  3162   3641   ** Initialize and deinitialize the operating system interface.
  3163   3642   */
  3164   3643   int sqlite3_os_init(void){
  3165   3644     static sqlite3_vfs winVfs = {
  3166   3645       3,                   /* iVersion */
................................................................................
  3178   3657       winDlSym,            /* xDlSym */
  3179   3658       winDlClose,          /* xDlClose */
  3180   3659       winRandomness,       /* xRandomness */
  3181   3660       winSleep,            /* xSleep */
  3182   3661       winCurrentTime,      /* xCurrentTime */
  3183   3662       winGetLastError,     /* xGetLastError */
  3184   3663       winCurrentTimeInt64, /* xCurrentTimeInt64 */
  3185         -    0,                   /* xSetSystemCall */
  3186         -    0,                   /* xGetSystemCall */
  3187         -    0,                   /* xNextSystemCall */
         3664  +    winSetSystemCall,    /* xSetSystemCall */
         3665  +    winGetSystemCall,    /* xGetSystemCall */
         3666  +    winNextSystemCall,   /* xNextSystemCall */
  3188   3667     };
         3668  +
         3669  +  /* Double-check that the aSyscall[] array has been constructed
         3670  +  ** correctly.  See ticket [bb3a86e890c8e96ab] */
         3671  +  assert( ArraySize(aSyscall)==60 );
  3189   3672   
  3190   3673   #ifndef SQLITE_OMIT_WAL
  3191   3674     /* get memory map allocation granularity */
  3192   3675     memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  3193         -  GetSystemInfo(&winSysInfo);
         3676  +  osGetSystemInfo(&winSysInfo);
  3194   3677     assert(winSysInfo.dwAllocationGranularity > 0);
  3195   3678   #endif
  3196   3679   
  3197   3680     sqlite3_vfs_register(&winVfs, 1);
  3198   3681     return SQLITE_OK; 
  3199   3682   }
         3683  +
  3200   3684   int sqlite3_os_end(void){ 
  3201   3685     return SQLITE_OK;
  3202   3686   }
  3203   3687   
  3204   3688   #endif /* SQLITE_OS_WIN */

Changes to src/pager.c.

   612    612     u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
   613    613     u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
   614    614     u8 useJournal;              /* Use a rollback journal on this file */
   615    615     u8 noReadlock;              /* Do not bother to obtain readlocks */
   616    616     u8 noSync;                  /* Do not sync the journal if true */
   617    617     u8 fullSync;                /* Do extra syncs of the journal for robustness */
   618    618     u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
          619  +  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
   619    620     u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
   620    621     u8 tempFile;                /* zFilename is a temporary file */
   621    622     u8 readOnly;                /* True for a read-only database */
   622    623     u8 memDb;                   /* True to inhibit all file I/O */
   623    624   
   624    625     /**************************************************************************
   625    626     ** The following block contains those class members that change during
................................................................................
   782    783   #ifndef SQLITE_OMIT_WAL
   783    784   static int pagerUseWal(Pager *pPager){
   784    785     return (pPager->pWal!=0);
   785    786   }
   786    787   #else
   787    788   # define pagerUseWal(x) 0
   788    789   # define pagerRollbackWal(x) 0
   789         -# define pagerWalFrames(v,w,x,y,z) 0
          790  +# define pagerWalFrames(v,w,x,y) 0
   790    791   # define pagerOpenWalIfPresent(z) SQLITE_OK
   791    792   # define pagerBeginReadTransaction(z) SQLITE_OK
   792    793   #endif
   793    794   
   794    795   #ifndef NDEBUG 
   795    796   /*
   796    797   ** Usage:
................................................................................
  2510   2511   **
  2511   2512   ** For temporary files the effective sector size is always 512 bytes.
  2512   2513   **
  2513   2514   ** Otherwise, for non-temporary files, the effective sector size is
  2514   2515   ** the value returned by the xSectorSize() method rounded up to 32 if
  2515   2516   ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  2516   2517   ** is greater than MAX_SECTOR_SIZE.
         2518  +**
         2519  +** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
         2520  +** the effective sector size to its minimum value (512).  The purpose of
         2521  +** pPager->sectorSize is to define the "blast radius" of bytes that
         2522  +** might change if a crash occurs while writing to a single byte in
         2523  +** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
         2524  +** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
         2525  +** size.  For backwards compatibility of the rollback journal file format,
         2526  +** we cannot reduce the effective sector size below 512.
  2517   2527   */
  2518   2528   static void setSectorSize(Pager *pPager){
  2519   2529     assert( isOpen(pPager->fd) || pPager->tempFile );
  2520   2530   
  2521         -  if( !pPager->tempFile ){
         2531  +  if( pPager->tempFile
         2532  +   || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
         2533  +              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
         2534  +  ){
  2522   2535       /* Sector size doesn't matter for temporary files. Also, the file
  2523   2536       ** may not have been opened yet, in which case the OsSectorSize()
  2524         -    ** call will segfault.
  2525         -    */
         2537  +    ** call will segfault. */
         2538  +    pPager->sectorSize = 512;
         2539  +  }else{
  2526   2540       pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
  2527         -  }
  2528         -  if( pPager->sectorSize<32 ){
  2529         -    pPager->sectorSize = 512;
  2530         -  }
  2531         -  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
  2532         -    assert( MAX_SECTOR_SIZE>=512 );
  2533         -    pPager->sectorSize = MAX_SECTOR_SIZE;
         2541  +    if( pPager->sectorSize<32 ){
         2542  +      pPager->sectorSize = 512;
         2543  +    }
         2544  +    if( pPager->sectorSize>MAX_SECTOR_SIZE ){
         2545  +      assert( MAX_SECTOR_SIZE>=512 );
         2546  +      pPager->sectorSize = MAX_SECTOR_SIZE;
         2547  +    }
  2534   2548     }
  2535   2549   }
  2536   2550   
  2537   2551   /*
  2538   2552   ** Playback the journal and thus restore the database file to
  2539   2553   ** the state it was in before we started making changes.  
  2540   2554   **
................................................................................
  2951   2965   ** The list of pages passed into this routine is always sorted by page number.
  2952   2966   ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  2953   2967   */ 
  2954   2968   static int pagerWalFrames(
  2955   2969     Pager *pPager,                  /* Pager object */
  2956   2970     PgHdr *pList,                   /* List of frames to log */
  2957   2971     Pgno nTruncate,                 /* Database size after this commit */
  2958         -  int isCommit,                   /* True if this is a commit */
  2959         -  int syncFlags                   /* Flags to pass to OsSync() (or 0) */
         2972  +  int isCommit                    /* True if this is a commit */
  2960   2973   ){
  2961   2974     int rc;                         /* Return code */
  2962   2975   #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  2963   2976     PgHdr *p;                       /* For looping over pages */
  2964   2977   #endif
  2965   2978   
  2966   2979     assert( pPager->pWal );
................................................................................
  2983   2996         if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
  2984   2997       }
  2985   2998       assert( pList );
  2986   2999     }
  2987   3000   
  2988   3001     if( pList->pgno==1 ) pager_write_changecounter(pList);
  2989   3002     rc = sqlite3WalFrames(pPager->pWal, 
  2990         -      pPager->pageSize, pList, nTruncate, isCommit, syncFlags
         3003  +      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  2991   3004     );
  2992   3005     if( rc==SQLITE_OK && pPager->pBackup ){
  2993   3006       PgHdr *p;
  2994   3007       for(p=pList; p; p=p->pDirty){
  2995   3008         sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  2996   3009       }
  2997   3010     }
................................................................................
  3263   3276   
  3264   3277     /* Finally,  rollback pages from the sub-journal.  Page that were
  3265   3278     ** previously rolled back out of the main journal (and are hence in pDone)
  3266   3279     ** will be skipped.  Out-of-range pages are also skipped.
  3267   3280     */
  3268   3281     if( pSavepoint ){
  3269   3282       u32 ii;            /* Loop counter */
  3270         -    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
         3283  +    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  3271   3284   
  3272   3285       if( pagerUseWal(pPager) ){
  3273   3286         rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  3274   3287       }
  3275   3288       for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  3276         -      assert( offset==ii*(4+pPager->pageSize) );
         3289  +      assert( offset==(i64)ii*(4+pPager->pageSize) );
  3277   3290         rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  3278   3291       }
  3279   3292       assert( rc!=SQLITE_DONE );
  3280   3293     }
  3281   3294   
  3282   3295     sqlite3BitvecDestroy(pDone);
  3283   3296     if( rc==SQLITE_OK ){
................................................................................
  3289   3302   
  3290   3303   /*
  3291   3304   ** Change the maximum number of in-memory pages that are allowed.
  3292   3305   */
  3293   3306   void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  3294   3307     sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  3295   3308   }
         3309  +
         3310  +/*
         3311  +** Free as much memory as possible from the pager.
         3312  +*/
         3313  +void sqlite3PagerShrink(Pager *pPager){
         3314  +  sqlite3PcacheShrink(pPager->pPCache);
         3315  +}
  3296   3316   
  3297   3317   /*
  3298   3318   ** Adjust the robustness of the database to damage due to OS crashes
  3299   3319   ** or power failures by changing the number of syncs()s when writing
  3300   3320   ** the rollback journal.  There are three levels:
  3301   3321   **
  3302   3322   **    OFF       sqlite3OsSync() is never called.  This is the default
................................................................................
  3356   3376     }else if( bCkptFullFsync ){
  3357   3377       pPager->syncFlags = SQLITE_SYNC_NORMAL;
  3358   3378       pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  3359   3379     }else{
  3360   3380       pPager->syncFlags = SQLITE_SYNC_NORMAL;
  3361   3381       pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  3362   3382     }
         3383  +  pPager->walSyncFlags = pPager->syncFlags;
         3384  +  if( pPager->fullSync ){
         3385  +    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
         3386  +  }
  3363   3387   }
  3364   3388   #endif
  3365   3389   
  3366   3390   /*
  3367   3391   ** The following global variable is incremented whenever the library
  3368   3392   ** attempts to open a temporary file.  This information is used for
  3369   3393   ** testing and analysis only.  
................................................................................
  4001   4025   
  4002   4026     /* Before the first write, give the VFS a hint of what the final
  4003   4027     ** file size will be.
  4004   4028     */
  4005   4029     assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  4006   4030     if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
  4007   4031       sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
         4032  +    sqlite3BeginBenignMalloc();
  4008   4033       sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
         4034  +    sqlite3EndBenignMalloc();
  4009   4035       pPager->dbHintSize = pPager->dbSize;
  4010   4036     }
  4011   4037   
  4012   4038     while( rc==SQLITE_OK && pList ){
  4013   4039       Pgno pgno = pList->pgno;
  4014   4040   
  4015   4041       /* If there are dirty pages in the page cache with page numbers greater
................................................................................
  4110   4136       );
  4111   4137       rc = openSubJournal(pPager);
  4112   4138   
  4113   4139       /* If the sub-journal was opened successfully (or was already open),
  4114   4140       ** write the journal record into the file.  */
  4115   4141       if( rc==SQLITE_OK ){
  4116   4142         void *pData = pPg->pData;
  4117         -      i64 offset = pPager->nSubRec*(4+pPager->pageSize);
         4143  +      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  4118   4144         char *pData2;
  4119   4145     
  4120   4146         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  4121   4147         PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  4122   4148         rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  4123   4149         if( rc==SQLITE_OK ){
  4124   4150           rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
................................................................................
  4183   4209     pPg->pDirty = 0;
  4184   4210     if( pagerUseWal(pPager) ){
  4185   4211       /* Write a single frame for this page to the log. */
  4186   4212       if( subjRequiresPage(pPg) ){ 
  4187   4213         rc = subjournalPage(pPg); 
  4188   4214       }
  4189   4215       if( rc==SQLITE_OK ){
  4190         -      rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
         4216  +      rc = pagerWalFrames(pPager, pPg, 0, 0);
  4191   4217       }
  4192   4218     }else{
  4193   4219     
  4194   4220       /* Sync the journal file if required. */
  4195   4221       if( pPg->flags&PGHDR_NEED_SYNC 
  4196   4222        || pPager->eState==PAGER_WRITER_CACHEMOD
  4197   4223       ){
................................................................................
  4342   4368       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  4343   4369       nPathname = sqlite3Strlen30(zPathname);
  4344   4370       z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  4345   4371       while( *z ){
  4346   4372         z += sqlite3Strlen30(z)+1;
  4347   4373         z += sqlite3Strlen30(z)+1;
  4348   4374       }
  4349         -    nUri = &z[1] - zUri;
         4375  +    nUri = (int)(&z[1] - zUri);
         4376  +    assert( nUri>=0 );
  4350   4377       if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  4351   4378         /* This branch is taken when the journal path required by
  4352   4379         ** the database being opened will be more than pVfs->mxPathname
  4353   4380         ** bytes in length. This means the database cannot be opened,
  4354   4381         ** as it will not be possible to open the journal file or even
  4355   4382         ** check for a hot-journal before reading.
  4356   4383         */
................................................................................
  4376   4403     */
  4377   4404     pPtr = (u8 *)sqlite3MallocZero(
  4378   4405       ROUND8(sizeof(*pPager)) +      /* Pager structure */
  4379   4406       ROUND8(pcacheSize) +           /* PCache object */
  4380   4407       ROUND8(pVfs->szOsFile) +       /* The main db file */
  4381   4408       journalFileSize * 2 +          /* The two journal files */ 
  4382   4409       nPathname + 1 + nUri +         /* zFilename */
  4383         -    nPathname + 8 + 1              /* zJournal */
         4410  +    nPathname + 8 + 2              /* zJournal */
  4384   4411   #ifndef SQLITE_OMIT_WAL
  4385         -    + nPathname + 4 + 1              /* zWal */
         4412  +    + nPathname + 4 + 2            /* zWal */
  4386   4413   #endif
  4387   4414     );
  4388   4415     assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  4389   4416     if( !pPtr ){
  4390   4417       sqlite3_free(zPathname);
  4391   4418       return SQLITE_NOMEM;
  4392   4419     }
................................................................................
  4401   4428     /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  4402   4429     if( zPathname ){
  4403   4430       assert( nPathname>0 );
  4404   4431       pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
  4405   4432       memcpy(pPager->zFilename, zPathname, nPathname);
  4406   4433       memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  4407   4434       memcpy(pPager->zJournal, zPathname, nPathname);
  4408         -    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
         4435  +    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+1);
  4409   4436       sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  4410   4437   #ifndef SQLITE_OMIT_WAL
  4411   4438       pPager->zWal = &pPager->zJournal[nPathname+8+1];
  4412   4439       memcpy(pPager->zWal, zPathname, nPathname);
  4413         -    memcpy(&pPager->zWal[nPathname], "-wal", 4);
         4440  +    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  4414   4441       sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  4415   4442   #endif
  4416   4443       sqlite3_free(zPathname);
  4417   4444     }
  4418   4445     pPager->pVfs = pVfs;
  4419   4446     pPager->vfsFlags = vfsFlags;
  4420   4447   
................................................................................
  4522   4549     assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  4523   4550     pPager->exclusiveMode = (u8)tempFile; 
  4524   4551     pPager->changeCountDone = pPager->tempFile;
  4525   4552     pPager->memDb = (u8)memDb;
  4526   4553     pPager->readOnly = (u8)readOnly;
  4527   4554     assert( useJournal || pPager->tempFile );
  4528   4555     pPager->noSync = pPager->tempFile;
  4529         -  pPager->fullSync = pPager->noSync ?0:1;
  4530         -  pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
  4531         -  pPager->ckptSyncFlags = pPager->syncFlags;
         4556  +  if( pPager->noSync ){
         4557  +    assert( pPager->fullSync==0 );
         4558  +    assert( pPager->syncFlags==0 );
         4559  +    assert( pPager->walSyncFlags==0 );
         4560  +    assert( pPager->ckptSyncFlags==0 );
         4561  +  }else{
         4562  +    pPager->fullSync = 1;
         4563  +    pPager->syncFlags = SQLITE_SYNC_NORMAL;
         4564  +    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
         4565  +    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
         4566  +  }
  4532   4567     /* pPager->pFirst = 0; */
  4533   4568     /* pPager->pFirstSynced = 0; */
  4534   4569     /* pPager->pLast = 0; */
  4535   4570     pPager->nExtra = (u16)nExtra;
  4536   4571     pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  4537   4572     assert( isOpen(pPager->fd) || tempFile );
  4538   4573     setSectorSize(pPager);
................................................................................
  5657   5692   int sqlite3PagerSync(Pager *pPager){
  5658   5693     int rc = SQLITE_OK;
  5659   5694     if( !pPager->noSync ){
  5660   5695       assert( !MEMDB );
  5661   5696       rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  5662   5697     }else if( isOpen(pPager->fd) ){
  5663   5698       assert( !MEMDB );
  5664         -    sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
         5699  +    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
         5700  +    if( rc==SQLITE_NOTFOUND ){
         5701  +      rc = SQLITE_OK;
         5702  +    }
  5665   5703     }
  5666   5704     return rc;
  5667   5705   }
  5668   5706   
  5669   5707   /*
  5670   5708   ** This function may only be called while a write-transaction is active in
  5671   5709   ** rollback. If the connection is in WAL mode, this call is a no-op. 
................................................................................
  5754   5792           ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  5755   5793           rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  5756   5794           pList = pPageOne;
  5757   5795           pList->pDirty = 0;
  5758   5796         }
  5759   5797         assert( rc==SQLITE_OK );
  5760   5798         if( ALWAYS(pList) ){
  5761         -        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1, 
  5762         -            (pPager->fullSync ? pPager->syncFlags : 0)
  5763         -        );
         5799  +        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  5764   5800         }
  5765   5801         sqlite3PagerUnref(pPageOne);
  5766   5802         if( rc==SQLITE_OK ){
  5767   5803           sqlite3PcacheCleanAll(pPager->pPCache);
  5768   5804         }
  5769   5805       }else{
  5770   5806         /* The following block updates the change-counter. Exactly how it
................................................................................
  6655   6691   ** in backup.c maintains the content of this variable. This module
  6656   6692   ** uses it opaquely as an argument to sqlite3BackupRestart() and
  6657   6693   ** sqlite3BackupUpdate() only.
  6658   6694   */
  6659   6695   sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  6660   6696     return &pPager->pBackup;
  6661   6697   }
         6698  +
         6699  +#ifndef SQLITE_OMIT_VACUUM
         6700  +/*
         6701  +** Unless this is an in-memory or temporary database, clear the pager cache.
         6702  +*/
         6703  +void sqlite3PagerClearCache(Pager *pPager){
         6704  +  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
         6705  +}
         6706  +#endif
  6662   6707   
  6663   6708   #ifndef SQLITE_OMIT_WAL
  6664   6709   /*
  6665   6710   ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  6666   6711   ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  6667   6712   ** or wal_blocking_checkpoint() API functions.
  6668   6713   **
................................................................................
  6832   6877                              pPager->pageSize, (u8*)pPager->pTmpSpace);
  6833   6878         pPager->pWal = 0;
  6834   6879       }
  6835   6880     }
  6836   6881     return rc;
  6837   6882   }
  6838   6883   
  6839         -/*
  6840         -** Unless this is an in-memory or temporary database, clear the pager cache.
  6841         -*/
  6842         -void sqlite3PagerClearCache(Pager *pPager){
  6843         -  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  6844         -}
  6845         -
  6846   6884   #ifdef SQLITE_HAS_CODEC
  6847   6885   /*
  6848   6886   ** This function is called by the wal module when writing page content
  6849   6887   ** into the log file.
  6850   6888   **
  6851   6889   ** This function returns a pointer to a buffer containing the encrypted
  6852   6890   ** page content. If a malloc fails, this function may return NULL.

Changes to src/pager.h.

    99     99   int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
   100    100   
   101    101   /* Functions used to configure a Pager object. */
   102    102   void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
   103    103   int sqlite3PagerSetPagesize(Pager*, u32*, int);
   104    104   int sqlite3PagerMaxPageCount(Pager*, int);
   105    105   void sqlite3PagerSetCachesize(Pager*, int);
          106  +void sqlite3PagerShrink(Pager*);
   106    107   void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
   107    108   int sqlite3PagerLockingMode(Pager *, int);
   108    109   int sqlite3PagerSetJournalMode(Pager *, int);
   109    110   int sqlite3PagerGetJournalMode(Pager*);
   110    111   int sqlite3PagerOkToChangeJournalMode(Pager*);
   111    112   i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
   112    113   sqlite3_backup **sqlite3PagerBackupPtr(Pager*);

Changes to src/parse.y.

    29     29   
    30     30   // This code runs whenever there is a syntax error
    31     31   //
    32     32   %syntax_error {
    33     33     UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
    34     34     assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
    35     35     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
    36         -  pParse->parseError = 1;
    37     36   }
    38     37   %stack_overflow {
    39     38     UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
    40     39     sqlite3ErrorMsg(pParse, "parser stack overflow");
    41         -  pParse->parseError = 1;
    42     40   }
    43     41   
    44     42   // The name of the generated procedure that implements the parser
    45     43   // is as follows:
    46     44   %name sqlite3Parser
    47     45   
    48     46   // The following text is included near the beginning of the C source
................................................................................
   392    390   %endif  SQLITE_OMIT_VIEW
   393    391   
   394    392   //////////////////////// The SELECT statement /////////////////////////////////
   395    393   //
   396    394   cmd ::= select(X).  {
   397    395     SelectDest dest = {SRT_Output, 0, 0, 0, 0};
   398    396     sqlite3Select(pParse, X, &dest);
          397  +  sqlite3ExplainBegin(pParse->pVdbe);
          398  +  sqlite3ExplainSelect(pParse->pVdbe, X);
          399  +  sqlite3ExplainFinish(pParse->pVdbe);
   399    400     sqlite3SelectDelete(pParse->db, X);
   400    401   }
   401    402   
   402    403   %type select {Select*}
   403    404   %destructor select {sqlite3SelectDelete(pParse->db, $$);}
   404    405   %type oneselect {Select*}
   405    406   %destructor oneselect {sqlite3SelectDelete(pParse->db, $$);}

Changes to src/pcache.c.

    16     16   /*
    17     17   ** A complete page cache is an instance of this structure.
    18     18   */
    19     19   struct PCache {
    20     20     PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
    21     21     PgHdr *pSynced;                     /* Last synced page in dirty page list */
    22     22     int nRef;                           /* Number of referenced pages */
    23         -  int nMax;                           /* Configured cache size */
           23  +  int szCache;                        /* Configured cache size */
    24     24     int szPage;                         /* Size of every page in this cache */
    25     25     int szExtra;                        /* Size of extra space for each page */
    26     26     int bPurgeable;                     /* True if pages are on backing store */
    27     27     int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
    28     28     void *pStress;                      /* Argument to xStress */
    29     29     sqlite3_pcache *pCache;             /* Pluggable cache module */
    30     30     PgHdr *pPage1;                      /* Reference to page 1 */
................................................................................
   127    127   */
   128    128   static void pcacheUnpin(PgHdr *p){
   129    129     PCache *pCache = p->pCache;
   130    130     if( pCache->bPurgeable ){
   131    131       if( p->pgno==1 ){
   132    132         pCache->pPage1 = 0;
   133    133       }
   134         -    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
          134  +    sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
   135    135     }
   136    136   }
   137    137   
   138    138   /*************************************************** General Interfaces ******
   139    139   **
   140    140   ** Initialize and shutdown the page cache subsystem. Neither of these 
   141    141   ** functions are threadsafe.
   142    142   */
   143    143   int sqlite3PcacheInitialize(void){
   144         -  if( sqlite3GlobalConfig.pcache.xInit==0 ){
          144  +  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
   145    145       /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
   146    146       ** built-in default page cache is used instead of the application defined
   147    147       ** page cache. */
   148    148       sqlite3PCacheSetDefault();
   149    149     }
   150         -  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
          150  +  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
   151    151   }
   152    152   void sqlite3PcacheShutdown(void){
   153         -  if( sqlite3GlobalConfig.pcache.xShutdown ){
          153  +  if( sqlite3GlobalConfig.pcache2.xShutdown ){
   154    154       /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
   155         -    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
          155  +    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
   156    156     }
   157    157   }
   158    158   
   159    159   /*
   160    160   ** Return the size in bytes of a PCache object.
   161    161   */
   162    162   int sqlite3PcacheSize(void){ return sizeof(PCache); }
................................................................................
   177    177   ){
   178    178     memset(p, 0, sizeof(PCache));
   179    179     p->szPage = szPage;
   180    180     p->szExtra = szExtra;
   181    181     p->bPurgeable = bPurgeable;
   182    182     p->xStress = xStress;
   183    183     p->pStress = pStress;
   184         -  p->nMax = 100;
          184  +  p->szCache = 100;
   185    185   }
   186    186   
   187    187   /*
   188    188   ** Change the page size for PCache object. The caller must ensure that there
   189    189   ** are no outstanding page references when this function is called.
   190    190   */
   191    191   void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
   192    192     assert( pCache->nRef==0 && pCache->pDirty==0 );
   193    193     if( pCache->pCache ){
   194         -    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
          194  +    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   195    195       pCache->pCache = 0;
   196    196       pCache->pPage1 = 0;
   197    197     }
   198    198     pCache->szPage = szPage;
   199    199   }
          200  +
          201  +/*
          202  +** Compute the number of pages of cache requested.
          203  +*/
          204  +static int numberOfCachePages(PCache *p){
          205  +  if( p->szCache>=0 ){
          206  +    return p->szCache;
          207  +  }else{
          208  +    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
          209  +  }
          210  +}
   200    211   
   201    212   /*
   202    213   ** Try to obtain a page from the cache.
   203    214   */
   204    215   int sqlite3PcacheFetch(
   205    216     PCache *pCache,       /* Obtain the page from this cache */
   206    217     Pgno pgno,            /* Page number to obtain */
   207    218     int createFlag,       /* If true, create page if it does not exist already */
   208    219     PgHdr **ppPage        /* Write the page here */
   209    220   ){
   210         -  PgHdr *pPage = 0;
          221  +  sqlite3_pcache_page *pPage = 0;
          222  +  PgHdr *pPgHdr = 0;
   211    223     int eCreate;
   212    224   
   213    225     assert( pCache!=0 );
   214    226     assert( createFlag==1 || createFlag==0 );
   215    227     assert( pgno>0 );
   216    228   
   217    229     /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
   218    230     ** allocate it now.
   219    231     */
   220    232     if( !pCache->pCache && createFlag ){
   221    233       sqlite3_pcache *p;
   222         -    int nByte;
   223         -    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
   224         -    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
          234  +    p = sqlite3GlobalConfig.pcache2.xCreate(
          235  +        pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
          236  +    );
   225    237       if( !p ){
   226    238         return SQLITE_NOMEM;
   227    239       }
   228         -    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
          240  +    sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
   229    241       pCache->pCache = p;
   230    242     }
   231    243   
   232    244     eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
   233    245     if( pCache->pCache ){
   234         -    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
          246  +    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
   235    247     }
   236    248   
   237    249     if( !pPage && eCreate==1 ){
   238    250       PgHdr *pPg;
   239    251   
   240    252       /* Find a dirty page to write-out and recycle. First try to find a 
   241    253       ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
................................................................................
   254    266       if( pPg ){
   255    267         int rc;
   256    268   #ifdef SQLITE_LOG_CACHE_SPILL
   257    269         sqlite3_log(SQLITE_FULL, 
   258    270                     "spill page %d making room for %d - cache used: %d/%d",
   259    271                     pPg->pgno, pgno,
   260    272                     sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
   261         -                  pCache->nMax);
          273  +                  numberOfCachePages(pCache));
   262    274   #endif
   263    275         rc = pCache->xStress(pCache->pStress, pPg);
   264    276         if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
   265    277           return rc;
   266    278         }
   267    279       }
   268    280   
   269         -    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
          281  +    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
   270    282     }
   271    283   
   272    284     if( pPage ){
   273         -    if( !pPage->pData ){
   274         -      memset(pPage, 0, sizeof(PgHdr));
   275         -      pPage->pData = (void *)&pPage[1];
   276         -      pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
   277         -      memset(pPage->pExtra, 0, pCache->szExtra);
   278         -      pPage->pCache = pCache;
   279         -      pPage->pgno = pgno;
          285  +    pPgHdr = (PgHdr *)pPage->pExtra;
          286  +
          287  +    if( !pPgHdr->pPage ){
          288  +      memset(pPgHdr, 0, sizeof(PgHdr));
          289  +      pPgHdr->pPage = pPage;
          290  +      pPgHdr->pData = pPage->pBuf;
          291  +      pPgHdr->pExtra = (void *)&pPgHdr[1];
          292  +      memset(pPgHdr->pExtra, 0, pCache->szExtra);
          293  +      pPgHdr->pCache = pCache;
          294  +      pPgHdr->pgno = pgno;
   280    295       }
   281         -    assert( pPage->pCache==pCache );
   282         -    assert( pPage->pgno==pgno );
   283         -    assert( pPage->pData==(void *)&pPage[1] );
   284         -    assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
          296  +    assert( pPgHdr->pCache==pCache );
          297  +    assert( pPgHdr->pgno==pgno );
          298  +    assert( pPgHdr->pData==pPage->pBuf );
          299  +    assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
   285    300   
   286         -    if( 0==pPage->nRef ){
          301  +    if( 0==pPgHdr->nRef ){
   287    302         pCache->nRef++;
   288    303       }
   289         -    pPage->nRef++;
          304  +    pPgHdr->nRef++;
   290    305       if( pgno==1 ){
   291         -      pCache->pPage1 = pPage;
          306  +      pCache->pPage1 = pPgHdr;
   292    307       }
   293    308     }
   294         -  *ppPage = pPage;
   295         -  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
          309  +  *ppPage = pPgHdr;
          310  +  return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
   296    311   }
   297    312   
   298    313   /*
   299    314   ** Decrement the reference count on a page. If the page is clean and the
   300    315   ** reference count drops to 0, then it is made elible for recycling.
   301    316   */
   302    317   void sqlite3PcacheRelease(PgHdr *p){
................................................................................
   335    350       pcacheRemoveFromDirtyList(p);
   336    351     }
   337    352     pCache = p->pCache;
   338    353     pCache->nRef--;
   339    354     if( p->pgno==1 ){
   340    355       pCache->pPage1 = 0;
   341    356     }
   342         -  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
          357  +  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
   343    358   }
   344    359   
   345    360   /*
   346    361   ** Make sure the page is marked as dirty. If it isn't dirty already,
   347    362   ** make it so.
   348    363   */
   349    364   void sqlite3PcacheMakeDirty(PgHdr *p){
................................................................................
   393    408   /*
   394    409   ** Change the page number of page p to newPgno. 
   395    410   */
   396    411   void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
   397    412     PCache *pCache = p->pCache;
   398    413     assert( p->nRef>0 );
   399    414     assert( newPgno>0 );
   400         -  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
          415  +  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
   401    416     p->pgno = newPgno;
   402    417     if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
   403    418       pcacheRemoveFromDirtyList(p);
   404    419       pcacheAddToDirtyList(p);
   405    420     }
   406    421   }
   407    422   
................................................................................
   430    445           sqlite3PcacheMakeClean(p);
   431    446         }
   432    447       }
   433    448       if( pgno==0 && pCache->pPage1 ){
   434    449         memset(pCache->pPage1->pData, 0, pCache->szPage);
   435    450         pgno = 1;
   436    451       }
   437         -    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
          452  +    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
   438    453     }
   439    454   }
   440    455   
   441    456   /*
   442    457   ** Close a cache.
   443    458   */
   444    459   void sqlite3PcacheClose(PCache *pCache){
   445    460     if( pCache->pCache ){
   446         -    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
          461  +    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
   447    462     }
   448    463   }
   449    464   
   450    465   /* 
   451    466   ** Discard the contents of the cache.
   452    467   */
   453    468   void sqlite3PcacheClear(PCache *pCache){
................................................................................
   551    566   
   552    567   /* 
   553    568   ** Return the total number of pages in the cache.
   554    569   */
   555    570   int sqlite3PcachePagecount(PCache *pCache){
   556    571     int nPage = 0;
   557    572     if( pCache->pCache ){
   558         -    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
          573  +    nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
   559    574     }
   560    575     return nPage;
   561    576   }
   562    577   
   563    578   #ifdef SQLITE_TEST
   564    579   /*
   565    580   ** Get the suggested cache-size value.
   566    581   */
   567    582   int sqlite3PcacheGetCachesize(PCache *pCache){
   568         -  return pCache->nMax;
          583  +  return numberOfCachePages(pCache);
   569    584   }
   570    585   #endif
   571    586   
   572    587   /*
   573    588   ** Set the suggested cache-size value.
   574    589   */
   575    590   void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
   576         -  pCache->nMax = mxPage;
          591  +  pCache->szCache = mxPage;
          592  +  if( pCache->pCache ){
          593  +    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
          594  +                                           numberOfCachePages(pCache));
          595  +  }
          596  +}
          597  +
          598  +/*
          599  +** Free up as much memory as possible from the page cache.
          600  +*/
          601  +void sqlite3PcacheShrink(PCache *pCache){
   577    602     if( pCache->pCache ){
   578         -    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
          603  +    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
   579    604     }
   580    605   }
   581    606   
   582    607   #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
   583    608   /*
   584    609   ** For all dirty pages currently in the cache, invoke the specified
   585    610   ** callback. This is only used if the SQLITE_CHECK_PAGES macro is

Changes to src/pcache.h.

    19     19   typedef struct PCache PCache;
    20     20   
    21     21   /*
    22     22   ** Every page in the cache is controlled by an instance of the following
    23     23   ** structure.
    24     24   */
    25     25   struct PgHdr {
    26         -  void *pData;                   /* Content of this page */
           26  +  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
           27  +  void *pData;                   /* Page data */
    27     28     void *pExtra;                  /* Extra content */
    28     29     PgHdr *pDirty;                 /* Transient list of dirty pages */
    29     30     Pgno pgno;                     /* Page number for this page */
    30     31     Pager *pPager;                 /* The pager this page is part of */
    31     32   #ifdef SQLITE_CHECK_PAGES
    32     33     u32 pageHash;                  /* Hash of page content */
    33     34   #endif
................................................................................
   136    137   ** the total number of pages cached by purgeable pager-caches to the sum
   137    138   ** of the suggested cache-sizes.
   138    139   */
   139    140   void sqlite3PcacheSetCachesize(PCache *, int);
   140    141   #ifdef SQLITE_TEST
   141    142   int sqlite3PcacheGetCachesize(PCache *);
   142    143   #endif
          144  +
          145  +/* Free up as much memory as possible from the page cache */
          146  +void sqlite3PcacheShrink(PCache*);
   143    147   
   144    148   #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   145    149   /* Try to return memory used by the pcache module to the main memory heap */
   146    150   int sqlite3PcacheReleaseMemory(int);
   147    151   #endif
   148    152   
   149    153   #ifdef SQLITE_TEST
   150    154   void sqlite3PcacheStats(int*,int*,int*,int*);
   151    155   #endif
   152    156   
   153    157   void sqlite3PCacheSetDefault(void);
   154    158   
   155    159   #endif /* _PCACHE_H_ */

Changes to src/pcache1.c.

    20     20   #include "sqliteInt.h"
    21     21   
    22     22   typedef struct PCache1 PCache1;
    23     23   typedef struct PgHdr1 PgHdr1;
    24     24   typedef struct PgFreeslot PgFreeslot;
    25     25   typedef struct PGroup PGroup;
    26     26   
    27         -
    28     27   /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
    29     28   ** of one or more PCaches that are able to recycle each others unpinned
    30     29   ** pages when they are under memory pressure.  A PGroup is an instance of
    31     30   ** the following object.
    32     31   **
    33     32   ** This page cache implementation works in one of two modes:
    34     33   **
................................................................................
    45     44   **
    46     45   ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
    47     46   ** PGroup which is the pcache1.grp global variable and its mutex is
    48     47   ** SQLITE_MUTEX_STATIC_LRU.
    49     48   */
    50     49   struct PGroup {
    51     50     sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
    52         -  int nMaxPage;                  /* Sum of nMax for purgeable caches */
    53         -  int nMinPage;                  /* Sum of nMin for purgeable caches */
    54         -  int mxPinned;                  /* nMaxpage + 10 - nMinPage */
    55         -  int nCurrentPage;              /* Number of purgeable pages allocated */
           51  +  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
           52  +  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
           53  +  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
           54  +  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
    56     55     PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
    57     56   };
    58     57   
    59     58   /* Each page cache is an instance of the following object.  Every
    60     59   ** open database file (including each in-memory database and each
    61     60   ** temporary or transient database) has a single page cache which
    62     61   ** is an instance of this object.
................................................................................
    68     67     /* Cache configuration parameters. Page size (szPage) and the purgeable
    69     68     ** flag (bPurgeable) are set when the cache is created. nMax may be 
    70     69     ** modified at any time by a call to the pcache1CacheSize() method.
    71     70     ** The PGroup mutex must be held when accessing nMax.
    72     71     */
    73     72     PGroup *pGroup;                     /* PGroup this cache belongs to */
    74     73     int szPage;                         /* Size of allocated pages in bytes */
           74  +  int szExtra;                        /* Size of extra space in bytes */
    75     75     int bPurgeable;                     /* True if cache is purgeable */
    76     76     unsigned int nMin;                  /* Minimum number of pages reserved */
    77     77     unsigned int nMax;                  /* Configured "cache_size" value */
    78     78     unsigned int n90pct;                /* nMax*9/10 */
    79     79   
    80     80     /* Hash table of all pages. The following variables may only be accessed
    81     81     ** when the accessor is holding the PGroup mutex.
................................................................................
    86     86     PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
    87     87   
    88     88     unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
    89     89   };
    90     90   
    91     91   /*
    92     92   ** Each cache entry is represented by an instance of the following 
    93         -** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
    94         -** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
    95         -** macro below).
           93  +** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
           94  +** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
           95  +** in memory.
    96     96   */
    97     97   struct PgHdr1 {
           98  +  sqlite3_pcache_page page;
    98     99     unsigned int iKey;             /* Key value (page number) */
    99    100     PgHdr1 *pNext;                 /* Next in hash table chain */
   100    101     PCache1 *pCache;               /* Cache that currently owns this page */
   101    102     PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
   102    103     PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
   103    104   };
   104    105   
................................................................................
   140    141   /*
   141    142   ** All code in this file should access the global structure above via the
   142    143   ** alias "pcache1". This ensures that the WSD emulation is used when
   143    144   ** compiling for systems that do not support real WSD.
   144    145   */
   145    146   #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
   146    147   
   147         -/*
   148         -** When a PgHdr1 structure is allocated, the associated PCache1.szPage
   149         -** bytes of data are located directly before it in memory (i.e. the total
   150         -** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
   151         -** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
   152         -** an argument and returns a pointer to the associated block of szPage
   153         -** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
   154         -** a pointer to a block of szPage bytes of data and the return value is
   155         -** a pointer to the associated PgHdr1 structure.
   156         -**
   157         -**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
   158         -*/
   159         -#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
   160         -#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
   161         -
   162    148   /*
   163    149   ** Macros to enter and leave the PCache LRU mutex.
   164    150   */
   165    151   #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
   166    152   #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
   167    153   
   168    154   /******************************************************************************/
................................................................................
   237    223     }
   238    224     return p;
   239    225   }
   240    226   
   241    227   /*
   242    228   ** Free an allocated buffer obtained from pcache1Alloc().
   243    229   */
   244         -static void pcache1Free(void *p){
   245         -  if( p==0 ) return;
          230  +static int pcache1Free(void *p){
          231  +  int nFreed = 0;
          232  +  if( p==0 ) return 0;
   246    233     if( p>=pcache1.pStart && p<pcache1.pEnd ){
   247    234       PgFreeslot *pSlot;
   248    235       sqlite3_mutex_enter(pcache1.mutex);
   249    236       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
   250    237       pSlot = (PgFreeslot*)p;
   251    238       pSlot->pNext = pcache1.pFree;
   252    239       pcache1.pFree = pSlot;
   253    240       pcache1.nFreeSlot++;
   254    241       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
   255    242       assert( pcache1.nFreeSlot<=pcache1.nSlot );
   256    243       sqlite3_mutex_leave(pcache1.mutex);
   257    244     }else{
   258         -    int iSize;
   259    245       assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
   260    246       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
   261         -    iSize = sqlite3MallocSize(p);
          247  +    nFreed = sqlite3MallocSize(p);
   262    248       sqlite3_mutex_enter(pcache1.mutex);
   263         -    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
          249  +    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
   264    250       sqlite3_mutex_leave(pcache1.mutex);
   265    251       sqlite3_free(p);
   266    252     }
          253  +  return nFreed;
   267    254   }
   268    255   
   269    256   #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   270    257   /*
   271    258   ** Return the size of a pcache allocation
   272    259   */
   273    260   static int pcache1MemSize(void *p){
................................................................................
   284    271   }
   285    272   #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
   286    273   
   287    274   /*
   288    275   ** Allocate a new page object initially associated with cache pCache.
   289    276   */
   290    277   static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
   291         -  int nByte = sizeof(PgHdr1) + pCache->szPage;
   292    278     PgHdr1 *p = 0;
   293    279     void *pPg;
   294    280   
   295    281     /* The group mutex must be released before pcache1Alloc() is called. This
   296    282     ** is because it may call sqlite3_release_memory(), which assumes that 
   297    283     ** this mutex is not held. */
   298    284     assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
   299    285     pcache1LeaveMutex(pCache->pGroup);
   300         -  pPg = pcache1Alloc(nByte);
          286  +#ifdef SQLITE_PCACHE_SEPARATE_HEADER
          287  +  pPg = pcache1Alloc(pCache->szPage);
          288  +  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
          289  +  if( !pPg || !p ){
          290  +    pcache1Free(pPg);
          291  +    sqlite3_free(p);
          292  +    pPg = 0;
          293  +  }
          294  +#else
          295  +  pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
          296  +  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
          297  +#endif
   301    298     pcache1EnterMutex(pCache->pGroup);
   302    299   
   303    300     if( pPg ){
   304         -    p = PAGE_TO_PGHDR1(pCache, pPg);
          301  +    p->page.pBuf = pPg;
          302  +    p->page.pExtra = &p[1];
   305    303       if( pCache->bPurgeable ){
   306    304         pCache->pGroup->nCurrentPage++;
   307    305       }
          306  +    return p;
   308    307     }
   309         -  return p;
          308  +  return 0;
   310    309   }
   311    310   
   312    311   /*
   313    312   ** Free a page object allocated by pcache1AllocPage().
   314    313   **
   315    314   ** The pointer is allowed to be NULL, which is prudent.  But it turns out
   316    315   ** that the current implementation happens to never call this routine
   317    316   ** with a NULL pointer, so we mark the NULL test with ALWAYS().
   318    317   */
   319    318   static void pcache1FreePage(PgHdr1 *p){
   320    319     if( ALWAYS(p) ){
   321    320       PCache1 *pCache = p->pCache;
   322    321       assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
   323         -    pcache1Free(PGHDR1_TO_PAGE(p));
          322  +    pcache1Free(p->page.pBuf);
          323  +#ifdef SQLITE_PCACHE_SEPARATE_HEADER
          324  +    sqlite3_free(p);
          325  +#endif
   324    326       if( pCache->bPurgeable ){
   325    327         pCache->pGroup->nCurrentPage--;
   326    328       }
   327    329     }
   328    330   }
   329    331   
   330    332   /*
................................................................................
   357    359   **
   358    360   ** Or, the heap is used for all page cache memory put the heap is
   359    361   ** under memory pressure, then again it is desirable to avoid
   360    362   ** allocating a new page cache entry in order to avoid stressing
   361    363   ** the heap even further.
   362    364   */
   363    365   static int pcache1UnderMemoryPressure(PCache1 *pCache){
   364         -  if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
          366  +  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
   365    367       return pcache1.bUnderPressure;
   366    368     }else{
   367    369       return sqlite3HeapNearlyFull();
   368    370     }
   369    371   }
   370    372   
   371    373   /******************************************************************************/
................................................................................
   548    550   }
   549    551   
   550    552   /*
   551    553   ** Implementation of the sqlite3_pcache.xCreate method.
   552    554   **
   553    555   ** Allocate a new cache.
   554    556   */
   555         -static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
          557  +static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
   556    558     PCache1 *pCache;      /* The newly created page cache */
   557    559     PGroup *pGroup;       /* The group the new page cache will belong to */
   558    560     int sz;               /* Bytes of memory required to allocate the new cache */
   559    561   
   560    562     /*
   561    563     ** The seperateCache variable is true if each PCache has its own private
   562    564     ** PGroup.  In other words, separateCache is true for mode (1) where no
................................................................................
   570    572     **      use separate caches (mode-1)
   571    573     */
   572    574   #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
   573    575     const int separateCache = 0;
   574    576   #else
   575    577     int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
   576    578   #endif
          579  +
          580  +  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
          581  +  assert( szExtra < 300 );
   577    582   
   578    583     sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
   579    584     pCache = (PCache1 *)sqlite3_malloc(sz);
   580    585     if( pCache ){
   581    586       memset(pCache, 0, sz);
   582    587       if( separateCache ){
   583    588         pGroup = (PGroup*)&pCache[1];
   584    589         pGroup->mxPinned = 10;
   585    590       }else{
   586    591         pGroup = &pcache1.grp;
   587    592       }
   588    593       pCache->pGroup = pGroup;
   589    594       pCache->szPage = szPage;
          595  +    pCache->szExtra = szExtra;
   590    596       pCache->bPurgeable = (bPurgeable ? 1 : 0);
   591    597       if( bPurgeable ){
   592    598         pCache->nMin = 10;
   593    599         pcache1EnterMutex(pGroup);
   594    600         pGroup->nMinPage += pCache->nMin;
   595    601         pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   596    602         pcache1LeaveMutex(pGroup);
................................................................................
   613    619       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   614    620       pCache->nMax = nMax;
   615    621       pCache->n90pct = pCache->nMax*9/10;
   616    622       pcache1EnforceMaxPage(pGroup);
   617    623       pcache1LeaveMutex(pGroup);
   618    624     }
   619    625   }
          626  +
          627  +/*
          628  +** Implementation of the sqlite3_pcache.xShrink method. 
          629  +**
          630  +** Free up as much memory as possible.
          631  +*/
          632  +static void pcache1Shrink(sqlite3_pcache *p){
          633  +  PCache1 *pCache = (PCache1*)p;
          634  +  if( pCache->bPurgeable ){
          635  +    PGroup *pGroup = pCache->pGroup;
          636  +    int savedMaxPage;
          637  +    pcache1EnterMutex(pGroup);
          638  +    savedMaxPage = pGroup->nMaxPage;
          639  +    pGroup->nMaxPage = 0;
          640  +    pcache1EnforceMaxPage(pGroup);
          641  +    pGroup->nMaxPage = savedMaxPage;
          642  +    pcache1LeaveMutex(pGroup);
          643  +  }
          644  +}
   620    645   
   621    646   /*
   622    647   ** Implementation of the sqlite3_pcache.xPagecount method. 
   623    648   */
   624    649   static int pcache1Pagecount(sqlite3_pcache *p){
   625    650     int n;
   626    651     PCache1 *pCache = (PCache1*)p;
................................................................................
   680    705   **
   681    706   **      then attempt to recycle a page from the LRU list. If it is the right
   682    707   **      size, return the recycled buffer. Otherwise, free the buffer and
   683    708   **      proceed to step 5. 
   684    709   **
   685    710   **   5. Otherwise, allocate and return a new page buffer.
   686    711   */
   687         -static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
   688         -  int nPinned;
          712  +static sqlite3_pcache_page *pcache1Fetch(
          713  +  sqlite3_pcache *p, 
          714  +  unsigned int iKey, 
          715  +  int createFlag
          716  +){
          717  +  unsigned int nPinned;
   689    718     PCache1 *pCache = (PCache1 *)p;
   690    719     PGroup *pGroup;
   691    720     PgHdr1 *pPage = 0;
   692    721   
   693    722     assert( pCache->bPurgeable || createFlag!=1 );
   694    723     assert( pCache->bPurgeable || pCache->nMin==0 );
   695    724     assert( pCache->bPurgeable==0 || pCache->nMin==10 );
................................................................................
   715    744     ** optimization:  The common case is to exit the module before reaching
   716    745     ** this point.
   717    746     */
   718    747   #ifdef SQLITE_MUTEX_OMIT
   719    748     pGroup = pCache->pGroup;
   720    749   #endif
   721    750   
   722         -
   723    751     /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
          752  +  assert( pCache->nPage >= pCache->nRecyclable );
   724    753     nPinned = pCache->nPage - pCache->nRecyclable;
   725         -  assert( nPinned>=0 );
   726    754     assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
   727    755     assert( pCache->n90pct == pCache->nMax*9/10 );
   728    756     if( createFlag==1 && (
   729    757           nPinned>=pGroup->mxPinned
   730         -     || nPinned>=(int)pCache->n90pct
          758  +     || nPinned>=pCache->n90pct
   731    759        || pcache1UnderMemoryPressure(pCache)
   732    760     )){
   733    761       goto fetch_out;
   734    762     }
   735    763   
   736    764     if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
   737    765       goto fetch_out;
................................................................................
   739    767   
   740    768     /* Step 4. Try to recycle a page. */
   741    769     if( pCache->bPurgeable && pGroup->pLruTail && (
   742    770            (pCache->nPage+1>=pCache->nMax)
   743    771         || pGroup->nCurrentPage>=pGroup->nMaxPage
   744    772         || pcache1UnderMemoryPressure(pCache)
   745    773     )){
   746         -    PCache1 *pOtherCache;
          774  +    PCache1 *pOther;
   747    775       pPage = pGroup->pLruTail;
   748    776       pcache1RemoveFromHash(pPage);
   749    777       pcache1PinPage(pPage);
   750         -    if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
          778  +    pOther = pPage->pCache;
          779  +
          780  +    /* We want to verify that szPage and szExtra are the same for pOther
          781  +    ** and pCache.  Assert that we can verify this by comparing sums. */
          782  +    assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
          783  +    assert( pCache->szExtra<512 );
          784  +    assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
          785  +    assert( pOther->szExtra<512 );
          786  +
          787  +    if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
   751    788         pcache1FreePage(pPage);
   752    789         pPage = 0;
   753    790       }else{
   754         -      pGroup->nCurrentPage -= 
   755         -               (pOtherCache->bPurgeable - pCache->bPurgeable);
          791  +      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
   756    792       }
   757    793     }
   758    794   
   759    795     /* Step 5. If a usable page buffer has still not been found, 
   760    796     ** attempt to allocate a new one. 
   761    797     */
   762    798     if( !pPage ){
................................................................................
   769    805       unsigned int h = iKey % pCache->nHash;
   770    806       pCache->nPage++;
   771    807       pPage->iKey = iKey;
   772    808       pPage->pNext = pCache->apHash[h];
   773    809       pPage->pCache = pCache;
   774    810       pPage->pLruPrev = 0;
   775    811       pPage->pLruNext = 0;
   776         -    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
          812  +    *(void **)pPage->page.pExtra = 0;
   777    813       pCache->apHash[h] = pPage;
   778    814     }
   779    815   
   780    816   fetch_out:
   781    817     if( pPage && iKey>pCache->iMaxKey ){
   782    818       pCache->iMaxKey = iKey;
   783    819     }
   784    820     pcache1LeaveMutex(pGroup);
   785         -  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
          821  +  return &pPage->page;
   786    822   }
   787    823   
   788    824   
   789    825   /*
   790    826   ** Implementation of the sqlite3_pcache.xUnpin method.
   791    827   **
   792    828   ** Mark a page as unpinned (eligible for asynchronous recycling).
   793    829   */
   794         -static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
          830  +static void pcache1Unpin(
          831  +  sqlite3_pcache *p, 
          832  +  sqlite3_pcache_page *pPg, 
          833  +  int reuseUnlikely
          834  +){
   795    835     PCache1 *pCache = (PCache1 *)p;
   796         -  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
          836  +  PgHdr1 *pPage = (PgHdr1 *)pPg;
   797    837     PGroup *pGroup = pCache->pGroup;
   798    838    
   799    839     assert( pPage->pCache==pCache );
   800    840     pcache1EnterMutex(pGroup);
   801    841   
   802    842     /* It is an error to call this function if the page is already 
   803    843     ** part of the PGroup LRU list.
................................................................................
   825    865   }
   826    866   
   827    867   /*
   828    868   ** Implementation of the sqlite3_pcache.xRekey method. 
   829    869   */
   830    870   static void pcache1Rekey(
   831    871     sqlite3_pcache *p,
   832         -  void *pPg,
          872  +  sqlite3_pcache_page *pPg,
   833    873     unsigned int iOld,
   834    874     unsigned int iNew
   835    875   ){
   836    876     PCache1 *pCache = (PCache1 *)p;
   837         -  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
          877  +  PgHdr1 *pPage = (PgHdr1 *)pPg;
   838    878     PgHdr1 **pp;
   839    879     unsigned int h; 
   840    880     assert( pPage->iKey==iOld );
   841    881     assert( pPage->pCache==pCache );
   842    882   
   843    883     pcache1EnterMutex(pCache->pGroup);
   844    884   
................................................................................
   884    924   */
   885    925   static void pcache1Destroy(sqlite3_pcache *p){
   886    926     PCache1 *pCache = (PCache1 *)p;
   887    927     PGroup *pGroup = pCache->pGroup;
   888    928     assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
   889    929     pcache1EnterMutex(pGroup);
   890    930     pcache1TruncateUnsafe(pCache, 0);
          931  +  assert( pGroup->nMaxPage >= pCache->nMax );
   891    932     pGroup->nMaxPage -= pCache->nMax;
          933  +  assert( pGroup->nMinPage >= pCache->nMin );
   892    934     pGroup->nMinPage -= pCache->nMin;
   893    935     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
   894    936     pcache1EnforceMaxPage(pGroup);
   895    937     pcache1LeaveMutex(pGroup);
   896    938     sqlite3_free(pCache->apHash);
   897    939     sqlite3_free(pCache);
   898    940   }
................................................................................
   899    941   
   900    942   /*
   901    943   ** This function is called during initialization (sqlite3_initialize()) to
   902    944   ** install the default pluggable cache module, assuming the user has not
   903    945   ** already provided an alternative.
   904    946   */
   905    947   void sqlite3PCacheSetDefault(void){
   906         -  static const sqlite3_pcache_methods defaultMethods = {
          948  +  static const sqlite3_pcache_methods2 defaultMethods = {
          949  +    1,                       /* iVersion */
   907    950       0,                       /* pArg */
   908    951       pcache1Init,             /* xInit */
   909    952       pcache1Shutdown,         /* xShutdown */
   910    953       pcache1Create,           /* xCreate */
   911    954       pcache1Cachesize,        /* xCachesize */
   912    955       pcache1Pagecount,        /* xPagecount */
   913    956       pcache1Fetch,            /* xFetch */
   914    957       pcache1Unpin,            /* xUnpin */
   915    958       pcache1Rekey,            /* xRekey */
   916    959       pcache1Truncate,         /* xTruncate */
   917         -    pcache1Destroy           /* xDestroy */
          960  +    pcache1Destroy,          /* xDestroy */
          961  +    pcache1Shrink            /* xShrink */
   918    962     };
   919         -  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
          963  +  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
   920    964   }
   921    965   
   922    966   #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
   923    967   /*
   924    968   ** This function is called to free superfluous dynamically allocated memory
   925    969   ** held by the pager system. Memory in use by any SQLite pager allocated
   926    970   ** by the current thread may be sqlite3_free()ed.
................................................................................
   933    977     int nFree = 0;
   934    978     assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
   935    979     assert( sqlite3_mutex_notheld(pcache1.mutex) );
   936    980     if( pcache1.pStart==0 ){
   937    981       PgHdr1 *p;
   938    982       pcache1EnterMutex(&pcache1.grp);
   939    983       while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
   940         -      nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
          984  +      nFree += pcache1MemSize(p->page.pBuf);
          985  +#ifdef SQLITE_PCACHE_SEPARATE_HEADER
          986  +      nFree += sqlite3MemSize(p);
          987  +#endif
   941    988         pcache1PinPage(p);
   942    989         pcache1RemoveFromHash(p);
   943    990         pcache1FreePage(p);
   944    991       }
   945    992       pcache1LeaveMutex(&pcache1.grp);
   946    993     }
   947    994     return nFree;
................................................................................
   961   1008   ){
   962   1009     PgHdr1 *p;
   963   1010     int nRecyclable = 0;
   964   1011     for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
   965   1012       nRecyclable++;
   966   1013     }
   967   1014     *pnCurrent = pcache1.grp.nCurrentPage;
   968         -  *pnMax = pcache1.grp.nMaxPage;
   969         -  *pnMin = pcache1.grp.nMinPage;
         1015  +  *pnMax = (int)pcache1.grp.nMaxPage;
         1016  +  *pnMin = (int)pcache1.grp.nMinPage;
   970   1017     *pnRecyclable = nRecyclable;
   971   1018   }
   972   1019   #endif

Changes to src/pragma.c.

   342    342   
   343    343     assert( pId2 );
   344    344     zDb = pId2->n>0 ? pDb->zName : 0;
   345    345     if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
   346    346       goto pragma_out;
   347    347     }
   348    348    
   349         -#ifndef SQLITE_OMIT_PAGER_PRAGMAS
          349  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
   350    350     /*
   351    351     **  PRAGMA [database.]default_cache_size
   352    352     **  PRAGMA [database.]default_cache_size=N
   353    353     **
   354    354     ** The first form reports the current persistent setting for the
   355    355     ** page cache size.  The value returned is the maximum number of
   356    356     ** pages in the page cache.  The second form sets both the current
................................................................................
   391    391         sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
   392    392         sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
   393    393         assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   394    394         pDb->pSchema->cache_size = size;
   395    395         sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   396    396       }
   397    397     }else
          398  +#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
   398    399   
          400  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
   399    401     /*
   400    402     **  PRAGMA [database.]page_size
   401    403     **  PRAGMA [database.]page_size=N
   402    404     **
   403    405     ** The first form reports the current setting for the
   404    406     ** database page size in bytes.  The second form sets the
   405    407     ** database page size value.  The value can only be set if
................................................................................
   412    414         int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
   413    415         returnSingleInt(pParse, "page_size", size);
   414    416       }else{
   415    417         /* Malloc may fail when setting the page-size, as there is an internal
   416    418         ** buffer that the pager module resizes using sqlite3_realloc().
   417    419         */
   418    420         db->nextPagesize = sqlite3Atoi(zRight);
   419         -      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
          421  +      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
   420    422           db->mallocFailed = 1;
   421    423         }
   422    424       }
   423    425     }else
   424    426   
   425    427     /*
   426    428     **  PRAGMA [database.]secure_delete
................................................................................
   452    454     **  PRAGMA [database.]max_page_count=N
   453    455     **
   454    456     ** The first form reports the current setting for the
   455    457     ** maximum number of pages in the database file.  The 
   456    458     ** second form attempts to change this setting.  Both
   457    459     ** forms return the current setting.
   458    460     **
          461  +  ** The absolute value of N is used.  This is undocumented and might
          462  +  ** change.  The only purpose is to provide an easy way to test
          463  +  ** the sqlite3AbsInt32() function.
          464  +  **
   459    465     **  PRAGMA [database.]page_count
   460    466     **
   461    467     ** Return the number of pages in the specified database.
   462    468     */
   463    469     if( sqlite3StrICmp(zLeft,"page_count")==0
   464    470      || sqlite3StrICmp(zLeft,"max_page_count")==0
   465    471     ){
................................................................................
   466    472       int iReg;
   467    473       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   468    474       sqlite3CodeVerifySchema(pParse, iDb);
   469    475       iReg = ++pParse->nMem;
   470    476       if( sqlite3Tolower(zLeft[0])=='p' ){
   471    477         sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
   472    478       }else{
   473         -      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
          479  +      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
          480  +                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
   474    481       }
   475    482       sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
   476    483       sqlite3VdbeSetNumCols(v, 1);
   477    484       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
   478    485     }else
   479    486   
   480    487     /*
................................................................................
   680    687   
   681    688   #ifndef SQLITE_OMIT_PAGER_PRAGMAS
   682    689     /*
   683    690     **  PRAGMA [database.]cache_size
   684    691     **  PRAGMA [database.]cache_size=N
   685    692     **
   686    693     ** The first form reports the current local setting for the
   687         -  ** page cache size.  The local setting can be different from
   688         -  ** the persistent cache size value that is stored in the database
   689         -  ** file itself.  The value returned is the maximum number of
   690         -  ** pages in the page cache.  The second form sets the local
   691         -  ** page cache size value.  It does not change the persistent
   692         -  ** cache size stored on the disk so the cache size will revert
   693         -  ** to its default value when the database is closed and reopened.
   694         -  ** N should be a positive integer.
          694  +  ** page cache size. The second form sets the local
          695  +  ** page cache size value.  If N is positive then that is the
          696  +  ** number of pages in the cache.  If N is negative, then the
          697  +  ** number of pages is adjusted so that the cache uses -N kibibytes
          698  +  ** of memory.
   695    699     */
   696    700     if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
   697    701       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
   698    702       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
   699    703       if( !zRight ){
   700    704         returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
   701    705       }else{
   702         -      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
          706  +      int size = sqlite3Atoi(zRight);
   703    707         pDb->pSchema->cache_size = size;
   704    708         sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   705    709       }
   706    710     }else
   707    711   
   708    712     /*
   709    713     **   PRAGMA temp_store
................................................................................
  1430   1434       }
  1431   1435       returnSingleInt(pParse, "wal_autocheckpoint", 
  1432   1436          db->xWalCallback==sqlite3WalDefaultHook ? 
  1433   1437              SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  1434   1438     }else
  1435   1439   #endif
  1436   1440   
         1441  +  /*
         1442  +  **  PRAGMA shrink_memory
         1443  +  **
         1444  +  ** This pragma attempts to free as much memory as possible from the
         1445  +  ** current database connection.
         1446  +  */
         1447  +  if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
         1448  +    sqlite3_db_release_memory(db);
         1449  +  }else
         1450  +
  1437   1451   #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  1438   1452     /*
  1439   1453     ** Report the current state of file logs for all databases
  1440   1454     */
  1441   1455     if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
  1442   1456       static const char *const azLockName[] = {
  1443   1457         "unlocked", "shared", "reserved", "pending", "exclusive"

Changes to src/prepare.c.

   274    274       }
   275    275     }else{
   276    276       DbSetProperty(db, iDb, DB_Empty);
   277    277     }
   278    278     pDb->pSchema->enc = ENC(db);
   279    279   
   280    280     if( pDb->pSchema->cache_size==0 ){
          281  +#ifndef SQLITE_OMIT_DEPRECATED
   281    282       size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
   282    283       if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
   283    284       pDb->pSchema->cache_size = size;
          285  +#else
          286  +    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
          287  +#endif
   284    288       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
   285    289     }
   286    290   
   287    291     /*
   288    292     ** file_format==1    Version 3.0.0.
   289    293     ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
   290    294     ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults

Changes to src/printf.c.

   132    132     return (char)digit;
   133    133   }
   134    134   #endif /* SQLITE_OMIT_FLOATING_POINT */
   135    135   
   136    136   /*
   137    137   ** Append N space characters to the given string buffer.
   138    138   */
   139         -static void appendSpace(StrAccum *pAccum, int N){
          139  +void sqlite3AppendSpace(StrAccum *pAccum, int N){
   140    140     static const char zSpaces[] = "                             ";
   141    141     while( N>=(int)sizeof(zSpaces)-1 ){
   142    142       sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
   143    143       N -= sizeof(zSpaces)-1;
   144    144     }
   145    145     if( N>0 ){
   146    146       sqlite3StrAccumAppend(pAccum, zSpaces, N);
................................................................................
   660    660       ** "length" characters long.  The field width is "width".  Do
   661    661       ** the output.
   662    662       */
   663    663       if( !flag_leftjustify ){
   664    664         register int nspace;
   665    665         nspace = width-length;
   666    666         if( nspace>0 ){
   667         -        appendSpace(pAccum, nspace);
          667  +        sqlite3AppendSpace(pAccum, nspace);
   668    668         }
   669    669       }
   670    670       if( length>0 ){
   671    671         sqlite3StrAccumAppend(pAccum, bufpt, length);
   672    672       }
   673    673       if( flag_leftjustify ){
   674    674         register int nspace;
   675    675         nspace = width-length;
   676    676         if( nspace>0 ){
   677         -        appendSpace(pAccum, nspace);
          677  +        sqlite3AppendSpace(pAccum, nspace);
   678    678         }
   679    679       }
   680    680       sqlite3_free(zExtra);
   681    681     }/* End for loop over the format string */
   682    682   } /* End of function */
   683    683   
   684    684   /*

Changes to src/resolve.c.

   795    795           int flags = pE->flags & EP_ExpCollate;
   796    796           sqlite3ExprDelete(db, pE);
   797    797           pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
   798    798           if( pE==0 ) return 1;
   799    799           pE->pColl = pColl;
   800    800           pE->flags |= EP_IntValue | flags;
   801    801           pE->u.iValue = iCol;
   802         -        pItem->iCol = (u16)iCol;
          802  +        pItem->iOrderByCol = (u16)iCol;
   803    803           pItem->done = 1;
   804    804         }else{
   805    805           moreToDo = 1;
   806    806         }
   807    807       }
   808    808       pSelect = pSelect->pNext;
   809    809     }
................................................................................
   844    844       sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
   845    845       return 1;
   846    846     }
   847    847   #endif
   848    848     pEList = pSelect->pEList;
   849    849     assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
   850    850     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
   851         -    if( pItem->iCol ){
   852         -      if( pItem->iCol>pEList->nExpr ){
          851  +    if( pItem->iOrderByCol ){
          852  +      if( pItem->iOrderByCol>pEList->nExpr ){
   853    853           resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
   854    854           return 1;
   855    855         }
   856         -      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
          856  +      resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
   857    857       }
   858    858     }
   859    859     return 0;
   860    860   }
   861    861   
   862    862   /*
   863    863   ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
................................................................................
   896    896       Expr *pE = pItem->pExpr;
   897    897       iCol = resolveAsName(pParse, pSelect->pEList, pE);
   898    898       if( iCol>0 ){
   899    899         /* If an AS-name match is found, mark this ORDER BY column as being
   900    900         ** a copy of the iCol-th result-set column.  The subsequent call to
   901    901         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
   902    902         ** copy of the iCol-th result-set expression. */
   903         -      pItem->iCol = (u16)iCol;
          903  +      pItem->iOrderByCol = (u16)iCol;
   904    904         continue;
   905    905       }
   906    906       if( sqlite3ExprIsInteger(pE, &iCol) ){
   907    907         /* The ORDER BY term is an integer constant.  Again, set the column
   908    908         ** number so that sqlite3ResolveOrderGroupBy() will convert the
   909    909         ** order-by term to a copy of the result-set expression */
   910    910         if( iCol<1 ){
   911    911           resolveOutOfRangeError(pParse, zType, i+1, nResult);
   912    912           return 1;
   913    913         }
   914         -      pItem->iCol = (u16)iCol;
          914  +      pItem->iOrderByCol = (u16)iCol;
   915    915         continue;
   916    916       }
   917    917   
   918    918       /* Otherwise, treat the ORDER BY term as an ordinary expression */
   919         -    pItem->iCol = 0;
          919  +    pItem->iOrderByCol = 0;
   920    920       if( sqlite3ResolveExprNames(pNC, pE) ){
   921    921         return 1;
   922    922       }
   923    923     }
   924    924     return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
   925    925   }
   926    926   

Changes to src/select.c.

  2215   2215     ** the ORDER BY clause covers every term of the result set.  Add
  2216   2216     ** terms to the ORDER BY clause as necessary.
  2217   2217     */
  2218   2218     if( op!=TK_ALL ){
  2219   2219       for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  2220   2220         struct ExprList_item *pItem;
  2221   2221         for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  2222         -        assert( pItem->iCol>0 );
  2223         -        if( pItem->iCol==i ) break;
         2222  +        assert( pItem->iOrderByCol>0 );
         2223  +        if( pItem->iOrderByCol==i ) break;
  2224   2224         }
  2225   2225         if( j==nOrderBy ){
  2226   2226           Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  2227   2227           if( pNew==0 ) return SQLITE_NOMEM;
  2228   2228           pNew->flags |= EP_IntValue;
  2229   2229           pNew->u.iValue = i;
  2230   2230           pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  2231         -        pOrderBy->a[nOrderBy++].iCol = (u16)i;
         2231  +        pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  2232   2232         }
  2233   2233       }
  2234   2234     }
  2235   2235   
  2236   2236     /* Compute the comparison permutation and keyinfo that is used with
  2237   2237     ** the permutation used to determine if the next
  2238   2238     ** row of results comes from selectA or selectB.  Also add explicit
................................................................................
  2240   2240     ** to the right and the left are evaluated, they use the correct
  2241   2241     ** collation.
  2242   2242     */
  2243   2243     aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  2244   2244     if( aPermute ){
  2245   2245       struct ExprList_item *pItem;
  2246   2246       for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  2247         -      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
  2248         -      aPermute[i] = pItem->iCol - 1;
         2247  +      assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
         2248  +      aPermute[i] = pItem->iOrderByCol - 1;
  2249   2249       }
  2250   2250       pKeyMerge =
  2251   2251         sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
  2252   2252       if( pKeyMerge ){
  2253   2253         pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  2254   2254         pKeyMerge->nField = (u16)nOrderBy;
  2255   2255         pKeyMerge->enc = ENC(db);
................................................................................
  2584   2584       }
  2585   2585     }
  2586   2586   }
  2587   2587   #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  2588   2588   
  2589   2589   #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  2590   2590   /*
  2591         -** This routine attempts to flatten subqueries in order to speed
  2592         -** execution.  It returns 1 if it makes changes and 0 if no flattening
  2593         -** occurs.
         2591  +** This routine attempts to flatten subqueries as a performance optimization.
         2592  +** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  2594   2593   **
  2595   2594   ** To understand the concept of flattening, consider the following
  2596   2595   ** query:
  2597   2596   **
  2598   2597   **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  2599   2598   **
  2600   2599   ** The default way of implementing this query is to execute the
................................................................................
  2628   2627   **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
  2629   2628   **        sub-queries that were excluded from this optimization. Restriction 
  2630   2629   **        (4) has since been expanded to exclude all DISTINCT subqueries.
  2631   2630   **
  2632   2631   **   (6)  The subquery does not use aggregates or the outer query is not
  2633   2632   **        DISTINCT.
  2634   2633   **
  2635         -**   (7)  The subquery has a FROM clause.
         2634  +**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
         2635  +**        A FROM clause, consider adding a FROM close with the special
         2636  +**        table sqlite_once that consists of a single row containing a
         2637  +**        single NULL.
  2636   2638   **
  2637   2639   **   (8)  The subquery does not use LIMIT or the outer query is not a join.
  2638   2640   **
  2639   2641   **   (9)  The subquery does not use LIMIT or the outer query does not use
  2640   2642   **        aggregates.
  2641   2643   **
  2642   2644   **  (10)  The subquery does not use aggregates or the outer query does not
................................................................................
  2661   2663   **
  2662   2664   **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
  2663   2665   **        compound clause made up entirely of non-aggregate queries, and 
  2664   2666   **        the parent query:
  2665   2667   **
  2666   2668   **          * is not itself part of a compound select,
  2667   2669   **          * is not an aggregate or DISTINCT query, and
  2668         -**          * has no other tables or sub-selects in the FROM clause.
         2670  +**          * is not a join
  2669   2671   **
  2670   2672   **        The parent and sub-query may contain WHERE clauses. Subject to
  2671   2673   **        rules (11), (13) and (14), they may also contain ORDER BY,
  2672         -**        LIMIT and OFFSET clauses.
         2674  +**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
         2675  +**        operator other than UNION ALL because all the other compound
         2676  +**        operators have an implied DISTINCT which is disallowed by
         2677  +**        restriction (4).
  2673   2678   **
  2674   2679   **  (18)  If the sub-query is a compound select, then all terms of the
  2675   2680   **        ORDER by clause of the parent must be simple references to 
  2676   2681   **        columns of the sub-query.
  2677   2682   **
  2678   2683   **  (19)  The subquery does not use LIMIT or the outer query does not
  2679   2684   **        have a WHERE clause.
  2680   2685   **
  2681   2686   **  (20)  If the sub-query is a compound select, then it must not use
  2682   2687   **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
  2683   2688   **        somewhat by saying that the terms of the ORDER BY clause must
  2684         -**        appear as unmodified result columns in the outer query.  But
         2689  +**        appear as unmodified result columns in the outer query.  But we
  2685   2690   **        have other optimizations in mind to deal with that case.
  2686   2691   **
  2687   2692   **  (21)  The subquery does not use LIMIT or the outer query is not
  2688   2693   **        DISTINCT.  (See ticket [752e1646fc]).
  2689   2694   **
  2690   2695   ** In this routine, the "p" parameter is a pointer to the outer query.
  2691   2696   ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
................................................................................
  2806   2811       }
  2807   2812       if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  2808   2813         return 0;
  2809   2814       }
  2810   2815       for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  2811   2816         testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  2812   2817         testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
         2818  +      assert( pSub->pSrc!=0 );
  2813   2819         if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  2814   2820          || (pSub1->pPrior && pSub1->op!=TK_ALL) 
  2815         -       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
         2821  +       || pSub1->pSrc->nSrc<1
  2816   2822         ){
  2817   2823           return 0;
  2818   2824         }
         2825  +      testcase( pSub1->pSrc->nSrc>1 );
  2819   2826       }
  2820   2827   
  2821   2828       /* Restriction 18. */
  2822   2829       if( p->pOrderBy ){
  2823   2830         int ii;
  2824   2831         for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  2825         -        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
         2832  +        if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  2826   2833         }
  2827   2834       }
  2828   2835     }
  2829   2836   
  2830   2837     /***** If we reach this point, flattening is permitted. *****/
  2831   2838   
  2832   2839     /* Authorize the subquery */
................................................................................
  3841   3848         int onceAddr = 0;
  3842   3849         int retAddr;
  3843   3850         assert( pItem->addrFillSub==0 );
  3844   3851         pItem->regReturn = ++pParse->nMem;
  3845   3852         topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  3846   3853         pItem->addrFillSub = topAddr+1;
  3847   3854         VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  3848         -      if( pItem->isCorrelated==0 && pParse->pTriggerTab==0 ){
         3855  +      if( pItem->isCorrelated==0 ){
  3849   3856           /* If the subquery is no correlated and if we are not inside of
  3850   3857           ** a trigger, then we only need to compute the value of the subquery
  3851   3858           ** once. */
  3852         -        int regOnce = ++pParse->nMem;
  3853         -        onceAddr = sqlite3VdbeAddOp1(v, OP_Once, regOnce);
         3859  +        onceAddr = sqlite3CodeOnce(pParse);
  3854   3860         }
  3855   3861         sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  3856   3862         explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  3857   3863         sqlite3Select(pParse, pSub, &dest);
  3858   3864         pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  3859   3865         if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  3860   3866         retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  3861   3867         VdbeComment((v, "end %s", pItem->pTab->zName));
  3862   3868         sqlite3VdbeChangeP1(v, topAddr, retAddr);
  3863         -
         3869  +      sqlite3ClearTempRegCache(pParse);
  3864   3870       }
  3865   3871       if( /*pParse->nErr ||*/ db->mallocFailed ){
  3866   3872         goto select_end;
  3867   3873       }
  3868   3874       pParse->nHeight -= sqlite3SelectExprHeight(p);
  3869   3875       pTabList = p->pSrc;
  3870   3876       if( !IgnorableOrderby(pDest) ){
................................................................................
  4151   4157         pParse->nMem += pGroupBy->nExpr;
  4152   4158         iBMem = pParse->nMem + 1;
  4153   4159         pParse->nMem += pGroupBy->nExpr;
  4154   4160         sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  4155   4161         VdbeComment((v, "clear abort flag"));
  4156   4162         sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  4157   4163         VdbeComment((v, "indicate accumulator empty"));
         4164  +      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  4158   4165   
  4159   4166         /* Begin a loop that will extract all source rows in GROUP BY order.
  4160   4167         ** This might involve two separate loops with an OP_Sort in between, or
  4161   4168         ** it might be a single loop that uses an index to extract information
  4162   4169         ** in the right order to begin with.
  4163   4170         */
  4164   4171         sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
................................................................................
  4490   4497     }
  4491   4498   
  4492   4499     sqlite3DbFree(db, sAggInfo.aCol);
  4493   4500     sqlite3DbFree(db, sAggInfo.aFunc);
  4494   4501     return rc;
  4495   4502   }
  4496   4503   
  4497         -#if defined(SQLITE_DEBUG)
         4504  +#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  4498   4505   /*
  4499         -*******************************************************************************
  4500         -** The following code is used for testing and debugging only.  The code
  4501         -** that follows does not appear in normal builds.
  4502         -**
  4503         -** These routines are used to print out the content of all or part of a 
  4504         -** parse structures such as Select or Expr.  Such printouts are useful
  4505         -** for helping to understand what is happening inside the code generator
  4506         -** during the execution of complex SELECT statements.
  4507         -**
  4508         -** These routine are not called anywhere from within the normal
  4509         -** code base.  Then are intended to be called from within the debugger
  4510         -** or from temporary "printf" statements inserted for debugging.
         4506  +** Generate a human-readable description of a the Select object.
  4511   4507   */
  4512         -void sqlite3PrintExpr(Expr *p){
  4513         -  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  4514         -    sqlite3DebugPrintf("(%s", p->u.zToken);
  4515         -  }else{
  4516         -    sqlite3DebugPrintf("(%d", p->op);
         4508  +static void explainOneSelect(Vdbe *pVdbe, Select *p){
         4509  +  sqlite3ExplainPrintf(pVdbe, "SELECT ");
         4510  +  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
         4511  +    if( p->selFlags & SF_Distinct ){
         4512  +      sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
         4513  +    }
         4514  +    if( p->selFlags & SF_Aggregate ){
         4515  +      sqlite3ExplainPrintf(pVdbe, "agg_flag ");
         4516  +    }
         4517  +    sqlite3ExplainNL(pVdbe);
         4518  +    sqlite3ExplainPrintf(pVdbe, "   ");
  4517   4519     }
  4518         -  if( p->pLeft ){
  4519         -    sqlite3DebugPrintf(" ");
  4520         -    sqlite3PrintExpr(p->pLeft);
  4521         -  }
  4522         -  if( p->pRight ){
  4523         -    sqlite3DebugPrintf(" ");
  4524         -    sqlite3PrintExpr(p->pRight);
  4525         -  }
  4526         -  sqlite3DebugPrintf(")");
  4527         -}
  4528         -void sqlite3PrintExprList(ExprList *pList){
  4529         -  int i;
  4530         -  for(i=0; i<pList->nExpr; i++){
  4531         -    sqlite3PrintExpr(pList->a[i].pExpr);
  4532         -    if( i<pList->nExpr-1 ){
  4533         -      sqlite3DebugPrintf(", ");
  4534         -    }
  4535         -  }
  4536         -}
  4537         -void sqlite3PrintSelect(Select *p, int indent){
  4538         -  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  4539         -  sqlite3PrintExprList(p->pEList);
  4540         -  sqlite3DebugPrintf("\n");
  4541         -  if( p->pSrc ){
  4542         -    char *zPrefix;
         4520  +  sqlite3ExplainExprList(pVdbe, p->pEList);
         4521  +  sqlite3ExplainNL(pVdbe);
         4522  +  if( p->pSrc && p->pSrc->nSrc ){
  4543   4523       int i;
  4544         -    zPrefix = "FROM";
         4524  +    sqlite3ExplainPrintf(pVdbe, "FROM ");
         4525  +    sqlite3ExplainPush(pVdbe);
  4545   4526       for(i=0; i<p->pSrc->nSrc; i++){
  4546   4527         struct SrcList_item *pItem = &p->pSrc->a[i];
  4547         -      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
  4548         -      zPrefix = "";
         4528  +      sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  4549   4529         if( pItem->pSelect ){
  4550         -        sqlite3DebugPrintf("(\n");
  4551         -        sqlite3PrintSelect(pItem->pSelect, indent+10);
  4552         -        sqlite3DebugPrintf("%*s)", indent+8, "");
         4530  +        sqlite3ExplainSelect(pVdbe, pItem->pSelect);
         4531  +        if( pItem->pTab ){
         4532  +          sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
         4533  +        }
  4553   4534         }else if( pItem->zName ){
  4554         -        sqlite3DebugPrintf("%s", pItem->zName);
  4555         -      }
  4556         -      if( pItem->pTab ){
  4557         -        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
         4535  +        sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  4558   4536         }
  4559   4537         if( pItem->zAlias ){
  4560         -        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
         4538  +        sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  4561   4539         }
  4562         -      if( i<p->pSrc->nSrc-1 ){
  4563         -        sqlite3DebugPrintf(",");
         4540  +      if( pItem->jointype & JT_LEFT ){
         4541  +        sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  4564   4542         }
  4565         -      sqlite3DebugPrintf("\n");
         4543  +      sqlite3ExplainNL(pVdbe);
  4566   4544       }
         4545  +    sqlite3ExplainPop(pVdbe);
  4567   4546     }
  4568   4547     if( p->pWhere ){
  4569         -    sqlite3DebugPrintf("%*s WHERE ", indent, "");
  4570         -    sqlite3PrintExpr(p->pWhere);
  4571         -    sqlite3DebugPrintf("\n");
         4548  +    sqlite3ExplainPrintf(pVdbe, "WHERE ");
         4549  +    sqlite3ExplainExpr(pVdbe, p->pWhere);
         4550  +    sqlite3ExplainNL(pVdbe);
  4572   4551     }
  4573   4552     if( p->pGroupBy ){
  4574         -    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
  4575         -    sqlite3PrintExprList(p->pGroupBy);
  4576         -    sqlite3DebugPrintf("\n");
         4553  +    sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
         4554  +    sqlite3ExplainExprList(pVdbe, p->pGroupBy);
         4555  +    sqlite3ExplainNL(pVdbe);
  4577   4556     }
  4578   4557     if( p->pHaving ){
  4579         -    sqlite3DebugPrintf("%*s HAVING ", indent, "");
  4580         -    sqlite3PrintExpr(p->pHaving);
  4581         -    sqlite3DebugPrintf("\n");
         4558  +    sqlite3ExplainPrintf(pVdbe, "HAVING ");
         4559  +    sqlite3ExplainExpr(pVdbe, p->pHaving);
         4560  +    sqlite3ExplainNL(pVdbe);
  4582   4561     }
  4583   4562     if( p->pOrderBy ){
  4584         -    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
  4585         -    sqlite3PrintExprList(p->pOrderBy);
  4586         -    sqlite3DebugPrintf("\n");
         4563  +    sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
         4564  +    sqlite3ExplainExprList(pVdbe, p->pOrderBy);
         4565  +    sqlite3ExplainNL(pVdbe);
         4566  +  }
         4567  +  if( p->pLimit ){
         4568  +    sqlite3ExplainPrintf(pVdbe, "LIMIT ");
         4569  +    sqlite3ExplainExpr(pVdbe, p->pLimit);
         4570  +    sqlite3ExplainNL(pVdbe);
         4571  +  }
         4572  +  if( p->pOffset ){
         4573  +    sqlite3ExplainPrintf(pVdbe, "OFFSET ");
         4574  +    sqlite3ExplainExpr(pVdbe, p->pOffset);
         4575  +    sqlite3ExplainNL(pVdbe);
         4576  +  }
         4577  +}
         4578  +void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
         4579  +  if( p==0 ){
         4580  +    sqlite3ExplainPrintf(pVdbe, "(null-select)");
         4581  +    return;
         4582  +  }
         4583  +  while( p->pPrior ) p = p->pPrior;
         4584  +  sqlite3ExplainPush(pVdbe);
         4585  +  while( p ){
         4586  +    explainOneSelect(pVdbe, p);
         4587  +    p = p->pNext;
         4588  +    if( p==0 ) break;
         4589  +    sqlite3ExplainNL(pVdbe);
         4590  +    sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  4587   4591     }
         4592  +  sqlite3ExplainPrintf(pVdbe, "END");
         4593  +  sqlite3ExplainPop(pVdbe);
  4588   4594   }
         4595  +
  4589   4596   /* End of the structure debug printing code
  4590   4597   *****************************************************************************/
  4591   4598   #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */

Changes to src/shell.c.

  1122   1122         }
  1123   1123   
  1124   1124         /* echo the sql statement if echo on */
  1125   1125         if( pArg && pArg->echoOn ){
  1126   1126           const char *zStmtSql = sqlite3_sql(pStmt);
  1127   1127           fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1128   1128         }
         1129  +
         1130  +      /* Output TESTCTRL_EXPLAIN text of requested */
         1131  +      if( pArg && pArg->mode==MODE_Explain ){
         1132  +        const char *zExplain = 0;
         1133  +        sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain);
         1134  +        if( zExplain && zExplain[0] ){
         1135  +          fprintf(pArg->out, "%s", zExplain);
         1136  +        }
         1137  +      }
  1129   1138   
  1130   1139         /* perform the first step.  this will tell us if we
  1131   1140         ** have a result set or not and how wide it is.
  1132   1141         */
  1133   1142         rc = sqlite3_step(pStmt);
  1134   1143         /* if we have a result set... */
  1135   1144         if( SQLITE_ROW == rc ){
................................................................................
  1392   1401     ".separator STRING      Change separator used by output mode and .import\n"
  1393   1402     ".show                  Show the current values for various settings\n"
  1394   1403     ".stats ON|OFF          Turn stats on or off\n"
  1395   1404     ".tables ?TABLE?        List names of tables\n"
  1396   1405     "                         If TABLE specified, only list tables matching\n"
  1397   1406     "                         LIKE pattern TABLE.\n"
  1398   1407     ".timeout MS            Try opening locked tables for MS milliseconds\n"
         1408  +  ".vfsname ?AUX?         Print the name of the VFS stack\n"
  1399   1409     ".width NUM1 NUM2 ...   Set column widths for \"column\" mode\n"
  1400   1410   ;
  1401   1411   
  1402   1412   static char zTimerHelp[] =
  1403   1413     ".timer ON|OFF          Turn the CPU timer measurement on or off\n"
  1404   1414   ;
  1405   1415   
................................................................................
  2081   2091         }else{
  2082   2092           zShellStatic = azArg[1];
  2083   2093           rc = sqlite3_exec(p->db,
  2084   2094             "SELECT sql FROM "
  2085   2095             "  (SELECT sql sql, type type, tbl_name tbl_name, name name"
  2086   2096             "     FROM sqlite_master UNION ALL"
  2087   2097             "   SELECT sql, type, tbl_name, name FROM sqlite_temp_master) "
  2088         -          "WHERE tbl_name LIKE shellstatic() AND type!='meta' AND sql NOTNULL "
         2098  +          "WHERE lower(tbl_name) LIKE shellstatic()"
         2099  +          "  AND type!='meta' AND sql NOTNULL "
  2089   2100             "ORDER BY substr(type,2,1), name",
  2090   2101             callback, &data, &zErrMsg);
  2091   2102           zShellStatic = 0;
  2092   2103         }
  2093   2104       }else{
  2094   2105         rc = sqlite3_exec(p->db,
  2095   2106            "SELECT sql FROM "
................................................................................
  2215   2226         { "benign_malloc_hooks",   SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS    },
  2216   2227         { "pending_byte",          SQLITE_TESTCTRL_PENDING_BYTE           },
  2217   2228         { "assert",                SQLITE_TESTCTRL_ASSERT                 },
  2218   2229         { "always",                SQLITE_TESTCTRL_ALWAYS                 },
  2219   2230         { "reserve",               SQLITE_TESTCTRL_RESERVE                },
  2220   2231         { "optimizations",         SQLITE_TESTCTRL_OPTIMIZATIONS          },
  2221   2232         { "iskeyword",             SQLITE_TESTCTRL_ISKEYWORD              },
  2222         -      { "pghdrsz",               SQLITE_TESTCTRL_PGHDRSZ                },
  2223   2233         { "scratchmalloc",         SQLITE_TESTCTRL_SCRATCHMALLOC          },
  2224   2234       };
  2225   2235       int testctrl = -1;
  2226   2236       int rc = 0;
  2227   2237       int i, n;
  2228   2238       open_db(p);
  2229   2239   
................................................................................
  2260   2270             }
  2261   2271             break;
  2262   2272   
  2263   2273           /* sqlite3_test_control(int) */
  2264   2274           case SQLITE_TESTCTRL_PRNG_SAVE:           
  2265   2275           case SQLITE_TESTCTRL_PRNG_RESTORE:        
  2266   2276           case SQLITE_TESTCTRL_PRNG_RESET:
  2267         -        case SQLITE_TESTCTRL_PGHDRSZ:             
  2268   2277             if( nArg==2 ){
  2269   2278               rc = sqlite3_test_control(testctrl);
  2270   2279               printf("%d (0x%08x)\n", rc, rc);
  2271   2280             } else {
  2272   2281               fprintf(stderr,"Error: testctrl %s takes no options\n", azArg[1]);
  2273   2282             }
  2274   2283             break;
................................................................................
  2332   2341     if( HAS_TIMER && c=='t' && n>=5 && strncmp(azArg[0], "timer", n)==0
  2333   2342      && nArg==2
  2334   2343     ){
  2335   2344       enableTimer = booleanValue(azArg[1]);
  2336   2345     }else
  2337   2346     
  2338   2347     if( c=='v' && strncmp(azArg[0], "version", n)==0 ){
  2339         -    printf("SQLite %s %s\n",
         2348  +    printf("SQLite %s %s\n" /*extra-version-info*/,
  2340   2349           sqlite3_libversion(), sqlite3_sourceid());
  2341   2350     }else
         2351  +
         2352  +  if( c=='v' && strncmp(azArg[0], "vfsname", n)==0 ){
         2353  +    const char *zDbName = nArg==2 ? azArg[1] : "main";
         2354  +    char *zVfsName = 0;
         2355  +    if( p->db ){
         2356  +      sqlite3_file_control(p->db, zDbName, SQLITE_FCNTL_VFSNAME, &zVfsName);
         2357  +      if( zVfsName ){
         2358  +        printf("%s\n", zVfsName);
         2359  +        sqlite3_free(zVfsName);
         2360  +      }
         2361  +    }
         2362  +  }else
  2342   2363   
  2343   2364     if( c=='w' && strncmp(azArg[0], "width", n)==0 && nArg>1 ){
  2344   2365       int j;
  2345   2366       assert( nArg<=ArraySize(azArg) );
  2346   2367       for(j=1; j<nArg && j<ArraySize(p->colWidth); j++){
  2347   2368         p->colWidth[j-1] = atoi(azArg[j]);
  2348   2369       }
................................................................................
  2929   2950       /* Run commands received from standard input
  2930   2951       */
  2931   2952       if( stdin_is_interactive ){
  2932   2953         char *zHome;
  2933   2954         char *zHistory = 0;
  2934   2955         int nHistory;
  2935   2956         printf(
  2936         -        "SQLite version %s %.19s\n"
         2957  +        "SQLite version %s %.19s\n" /*extra-version-info*/
  2937   2958           "Enter \".help\" for instructions\n"
  2938   2959           "Enter SQL statements terminated with a \";\"\n",
  2939   2960           sqlite3_libversion(), sqlite3_sourceid()
  2940   2961         );
  2941   2962         zHome = find_home_dir();
  2942   2963         if( zHome ){
  2943   2964           nHistory = strlen30(zHome) + 20;

Changes to src/sqlite.h.in.

   168    168   const char *sqlite3_compileoption_get(int N);
   169    169   #endif
   170    170   
   171    171   /*
   172    172   ** CAPI3REF: Test To See If The Library Is Threadsafe
   173    173   **
   174    174   ** ^The sqlite3_threadsafe() function returns zero if and only if
   175         -** SQLite was compiled mutexing code omitted due to the
          175  +** SQLite was compiled with mutexing code omitted due to the
   176    176   ** [SQLITE_THREADSAFE] compile-time option being set to 0.
   177    177   **
   178    178   ** SQLite can be compiled with or without mutexes.  When
   179    179   ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
   180    180   ** are enabled and SQLite is threadsafe.  When the
   181    181   ** [SQLITE_THREADSAFE] macro is 0, 
   182    182   ** the mutexes are omitted.  Without the mutexes, it is not safe
................................................................................
   362    362   
   363    363   /*
   364    364   ** CAPI3REF: Result Codes
   365    365   ** KEYWORDS: SQLITE_OK {error code} {error codes}
   366    366   ** KEYWORDS: {result code} {result codes}
   367    367   **
   368    368   ** Many SQLite functions return an integer result code from the set shown
   369         -** here in order to indicates success or failure.
          369  +** here in order to indicate success or failure.
   370    370   **
   371    371   ** New error codes may be added in future versions of SQLite.
   372    372   **
   373    373   ** See also: [SQLITE_IOERR_READ | extended result codes],
   374    374   ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
   375    375   */
   376    376   #define SQLITE_OK           0   /* Successful result */
................................................................................
   500    500   ** mean that writes of blocks that are nnn bytes in size and
   501    501   ** are aligned to an address which is an integer multiple of
   502    502   ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
   503    503   ** that when data is appended to a file, the data is appended
   504    504   ** first then the size of the file is extended, never the other
   505    505   ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
   506    506   ** information is written to disk in the same order as calls
   507         -** to xWrite().
          507  +** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
          508  +** after reboot following a crash or power loss, the only bytes in a
          509  +** file that were written at the application level might have changed
          510  +** and that adjacent bytes, even bytes within the same sector are
          511  +** guaranteed to be unchanged.
   508    512   */
   509    513   #define SQLITE_IOCAP_ATOMIC                 0x00000001
   510    514   #define SQLITE_IOCAP_ATOMIC512              0x00000002
   511    515   #define SQLITE_IOCAP_ATOMIC1K               0x00000004
   512    516   #define SQLITE_IOCAP_ATOMIC2K               0x00000008
   513    517   #define SQLITE_IOCAP_ATOMIC4K               0x00000010
   514    518   #define SQLITE_IOCAP_ATOMIC8K               0x00000020
   515    519   #define SQLITE_IOCAP_ATOMIC16K              0x00000040
   516    520   #define SQLITE_IOCAP_ATOMIC32K              0x00000080
   517    521   #define SQLITE_IOCAP_ATOMIC64K              0x00000100
   518    522   #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
   519    523   #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
   520    524   #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
          525  +#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
   521    526   
   522    527   /*
   523    528   ** CAPI3REF: File Locking Levels
   524    529   **
   525    530   ** SQLite uses one of these integer values as the second
   526    531   ** argument to calls it makes to the xLock() and xUnlock() methods
   527    532   ** of an [sqlite3_io_methods] object.
................................................................................
   735    740   ** VFSes do not need this signal and should silently ignore this opcode.
   736    741   ** Applications should not call [sqlite3_file_control()] with this
   737    742   ** opcode as doing so may disrupt the operation of the specialized VFSes
   738    743   ** that do require it.  
   739    744   **
   740    745   ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
   741    746   ** retry counts and intervals for certain disk I/O operations for the
   742         -** windows [VFS] in order to work to provide robustness against
          747  +** windows [VFS] in order to provide robustness in the presence of
   743    748   ** anti-virus programs.  By default, the windows VFS will retry file read,
   744    749   ** file write, and file delete operations up to 10 times, with a delay
   745    750   ** of 25 milliseconds before the first retry and with the delay increasing
   746    751   ** by an additional 25 milliseconds with each subsequent retry.  This
   747         -** opcode allows those to values (10 retries and 25 milliseconds of delay)
          752  +** opcode allows these two values (10 retries and 25 milliseconds of delay)
   748    753   ** to be adjusted.  The values are changed for all database connections
   749    754   ** within the same process.  The argument is a pointer to an array of two
   750    755   ** integers where the first integer i the new retry count and the second
   751    756   ** integer is the delay.  If either integer is negative, then the setting
   752    757   ** is not changed but instead the prior value of that setting is written
   753    758   ** into the array entry, allowing the current retry settings to be
   754    759   ** interrogated.  The zDbName parameter is ignored.
................................................................................
   762    767   ** have write permission on the directory containing the database file want
   763    768   ** to read the database file, as the WAL and shared memory files must exist
   764    769   ** in order for the database to be readable.  The fourth parameter to
   765    770   ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
   766    771   ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
   767    772   ** WAL mode.  If the integer is -1, then it is overwritten with the current
   768    773   ** WAL persistence setting.
          774  +**
          775  +** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
          776  +** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
          777  +** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
          778  +** xDeviceCharacteristics methods. The fourth parameter to
          779  +** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
          780  +** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
          781  +** mode.  If the integer is -1, then it is overwritten with the current
          782  +** zero-damage mode setting.
   769    783   **
   770    784   ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
   771    785   ** a write transaction to indicate that, unless it is rolled back for some
   772    786   ** reason, the entire database file will be overwritten by the current 
   773    787   ** transaction. This is used by VACUUM operations.
          788  +**
          789  +** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
          790  +** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
          791  +** final bottom-level VFS are written into memory obtained from 
          792  +** [sqlite3_malloc()] and the result is stored in the char* variable
          793  +** that the fourth parameter of [sqlite3_file_control()] points to.
          794  +** The caller is responsible for freeing the memory when done.  As with
          795  +** all file-control actions, there is no guarantee that this will actually
          796  +** do anything.  Callers should initialize the char* variable to a NULL
          797  +** pointer in case this file-control is not implemented.  This file-control
          798  +** is intended for diagnostic use only.
   774    799   */
   775         -#define SQLITE_FCNTL_LOCKSTATE        1
   776         -#define SQLITE_GET_LOCKPROXYFILE      2
   777         -#define SQLITE_SET_LOCKPROXYFILE      3
   778         -#define SQLITE_LAST_ERRNO             4
   779         -#define SQLITE_FCNTL_SIZE_HINT        5
   780         -#define SQLITE_FCNTL_CHUNK_SIZE       6
   781         -#define SQLITE_FCNTL_FILE_POINTER     7
   782         -#define SQLITE_FCNTL_SYNC_OMITTED     8
   783         -#define SQLITE_FCNTL_WIN32_AV_RETRY   9
   784         -#define SQLITE_FCNTL_PERSIST_WAL     10
   785         -#define SQLITE_FCNTL_OVERWRITE       11
          800  +#define SQLITE_FCNTL_LOCKSTATE               1
          801  +#define SQLITE_GET_LOCKPROXYFILE             2
          802  +#define SQLITE_SET_LOCKPROXYFILE             3
          803  +#define SQLITE_LAST_ERRNO                    4
          804  +#define SQLITE_FCNTL_SIZE_HINT               5
          805  +#define SQLITE_FCNTL_CHUNK_SIZE              6
          806  +#define SQLITE_FCNTL_FILE_POINTER            7
          807  +#define SQLITE_FCNTL_SYNC_OMITTED            8
          808  +#define SQLITE_FCNTL_WIN32_AV_RETRY          9
          809  +#define SQLITE_FCNTL_PERSIST_WAL            10
          810  +#define SQLITE_FCNTL_OVERWRITE              11
          811  +#define SQLITE_FCNTL_VFSNAME                12
          812  +#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
   786    813   
   787    814   /*
   788    815   ** CAPI3REF: Mutex Handle
   789    816   **
   790    817   ** The mutex module within SQLite defines [sqlite3_mutex] to be an
   791    818   ** abstract type for a mutex object.  The SQLite core never looks
   792    819   ** at the internal representation of an [sqlite3_mutex].  It only
................................................................................
   833    860   **
   834    861   ** [[sqlite3_vfs.xOpen]]
   835    862   ** ^SQLite guarantees that the zFilename parameter to xOpen
   836    863   ** is either a NULL pointer or string obtained
   837    864   ** from xFullPathname() with an optional suffix added.
   838    865   ** ^If a suffix is added to the zFilename parameter, it will
   839    866   ** consist of a single "-" character followed by no more than
   840         -** 10 alphanumeric and/or "-" characters.
          867  +** 11 alphanumeric and/or "-" characters.
   841    868   ** ^SQLite further guarantees that
   842    869   ** the string will be valid and unchanged until xClose() is
   843    870   ** called. Because of the previous sentence,
   844    871   ** the [sqlite3_file] can safely store a pointer to the
   845    872   ** filename if it needs to remember the filename for some reason.
   846    873   ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
   847    874   ** must invent its own temporary name for the file.  ^Whenever the 
................................................................................
  1364   1391   ** scratch memory beyond what is provided by this configuration option, then 
  1365   1392   ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1366   1393   **
  1367   1394   ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1368   1395   ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1369   1396   ** the database page cache with the default page cache implementation.  
  1370   1397   ** This configuration should not be used if an application-define page
  1371         -** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
         1398  +** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1372   1399   ** There are three arguments to this option: A pointer to 8-byte aligned
  1373   1400   ** memory, the size of each page buffer (sz), and the number of pages (N).
  1374   1401   ** The sz argument should be the size of the largest database page
  1375   1402   ** (a power of two between 512 and 32768) plus a little extra for each
  1376   1403   ** page header.  ^The page header size is 20 to 40 bytes depending on
  1377   1404   ** the host architecture.  ^It is harmless, apart from the wasted memory,
  1378   1405   ** to make sz a little too large.  The first
................................................................................
  1433   1460   ** [database connection].  The first argument is the
  1434   1461   ** size of each lookaside buffer slot and the second is the number of
  1435   1462   ** slots allocated to each database connection.)^  ^(This option sets the
  1436   1463   ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1437   1464   ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1438   1465   ** configuration on individual connections.)^ </dd>
  1439   1466   **
  1440         -** [[SQLITE_CONFIG_PCACHE]] <dt>SQLITE_CONFIG_PCACHE</dt>
         1467  +** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1441   1468   ** <dd> ^(This option takes a single argument which is a pointer to
  1442         -** an [sqlite3_pcache_methods] object.  This object specifies the interface
         1469  +** an [sqlite3_pcache_methods2] object.  This object specifies the interface
  1443   1470   ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
  1444   1471   ** object and uses it for page cache memory allocations.</dd>
  1445   1472   **
  1446         -** [[SQLITE_CONFIG_GETPCACHE]] <dt>SQLITE_CONFIG_GETPCACHE</dt>
         1473  +** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1447   1474   ** <dd> ^(This option takes a single argument which is a pointer to an
  1448         -** [sqlite3_pcache_methods] object.  SQLite copies of the current
         1475  +** [sqlite3_pcache_methods2] object.  SQLite copies of the current
  1449   1476   ** page cache implementation into that object.)^ </dd>
  1450   1477   **
  1451   1478   ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1452   1479   ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1453   1480   ** function with a call signature of void(*)(void*,int,const char*), 
  1454   1481   ** and a pointer to void. ^If the function pointer is not NULL, it is
  1455   1482   ** invoked by [sqlite3_log()] to process each logging event.  ^If the
................................................................................
  1474   1501   ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1475   1502   ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1476   1503   ** connection is opened. If it is globally disabled, filenames are
  1477   1504   ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1478   1505   ** database connection is opened. By default, URI handling is globally
  1479   1506   ** disabled. The default value may be changed by compiling with the
  1480   1507   ** [SQLITE_USE_URI] symbol defined.
         1508  +**
         1509  +** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
         1510  +** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFNIG_GETPCACHE
         1511  +** <dd> These options are obsolete and should not be used by new code.
         1512  +** They are retained for backwards compatibility but are now no-ops.
  1481   1513   ** </dl>
  1482   1514   */
  1483   1515   #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  1484   1516   #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  1485   1517   #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  1486   1518   #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
  1487   1519   #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
................................................................................
  1489   1521   #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
  1490   1522   #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
  1491   1523   #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
  1492   1524   #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
  1493   1525   #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
  1494   1526   /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
  1495   1527   #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
  1496         -#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
  1497         -#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
         1528  +#define SQLITE_CONFIG_PCACHE       14  /* no-op */
         1529  +#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
  1498   1530   #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
  1499   1531   #define SQLITE_CONFIG_URI          17  /* int */
         1532  +#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
         1533  +#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
  1500   1534   
  1501   1535   /*
  1502   1536   ** CAPI3REF: Database Connection Configuration Options
  1503   1537   **
  1504   1538   ** These constants are the available integer configuration options that
  1505   1539   ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1506   1540   **
................................................................................
  1977   2011   ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  1978   2012   **
  1979   2013   ** These routines all implement some additional formatting
  1980   2014   ** options that are useful for constructing SQL statements.
  1981   2015   ** All of the usual printf() formatting options apply.  In addition, there
  1982   2016   ** is are "%q", "%Q", and "%z" options.
  1983   2017   **
  1984         -** ^(The %q option works like %s in that it substitutes a null-terminated
         2018  +** ^(The %q option works like %s in that it substitutes a nul-terminated
  1985   2019   ** string from the argument list.  But %q also doubles every '\'' character.
  1986   2020   ** %q is designed for use inside a string literal.)^  By doubling each '\''
  1987   2021   ** character it escapes that character and allows it to be inserted into
  1988   2022   ** the string.
  1989   2023   **
  1990   2024   ** For example, assume the string variable zText contains text as follows:
  1991   2025   **
................................................................................
  2585   2619     int flags,              /* Flags */
  2586   2620     const char *zVfs        /* Name of VFS module to use */
  2587   2621   );
  2588   2622   
  2589   2623   /*
  2590   2624   ** CAPI3REF: Obtain Values For URI Parameters
  2591   2625   **
  2592         -** This is a utility routine, useful to VFS implementations, that checks
         2626  +** These are utility routines, useful to VFS implementations, that check
  2593   2627   ** to see if a database file was a URI that contained a specific query 
  2594         -** parameter, and if so obtains the value of the query parameter.
         2628  +** parameter, and if so obtains the value of that query parameter.
  2595   2629   **
  2596         -** The zFilename argument is the filename pointer passed into the xOpen()
  2597         -** method of a VFS implementation.  The zParam argument is the name of the
  2598         -** query parameter we seek.  This routine returns the value of the zParam
  2599         -** parameter if it exists.  If the parameter does not exist, this routine
  2600         -** returns a NULL pointer.
         2630  +** If F is the filename pointer passed into the xOpen() method of a VFS
         2631  +** implementation and P is the name of the query parameter, then
         2632  +** sqlite3_uri_parameter(F,P) returns the value of the P
         2633  +** parameter if it exists or a NULL pointer if P does not appear as a 
         2634  +** query parameter on F.  If P is a query parameter of F
         2635  +** has no explicit value, then sqlite3_uri_parameter(F,P) returns
         2636  +** a pointer to an empty string.
  2601   2637   **
  2602         -** If the zFilename argument to this function is not a pointer that SQLite
  2603         -** passed into the xOpen VFS method, then the behavior of this routine
  2604         -** is undefined and probably undesirable.
         2638  +** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
         2639  +** parameter and returns true (1) or false (0) according to the value
         2640  +** of P.  The value of P is true if it is "yes" or "true" or "on" or 
         2641  +** a non-zero number and is false otherwise.  If P is not a query parameter
         2642  +** on F then sqlite3_uri_boolean(F,P,B) returns (B!=0).
         2643  +**
         2644  +** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
         2645  +** 64-bit signed integer and returns that integer, or D if P does not
         2646  +** exist.  If the value of P is something other than an integer, then
         2647  +** zero is returned.
         2648  +** 
         2649  +** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
         2650  +** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
         2651  +** is not a pathname pointer that SQLite passed into the xOpen VFS method,
         2652  +** then the behavior of this routine is undefined and probably undesirable.
  2605   2653   */
  2606   2654   const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
         2655  +int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
         2656  +sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  2607   2657   
  2608   2658   
  2609   2659   /*
  2610   2660   ** CAPI3REF: Error Codes And Messages
  2611   2661   **
  2612   2662   ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  2613   2663   ** [extended result code] for the most recent failed sqlite3_* API call
................................................................................
  2921   2971   ** database.  ^The [ATTACH] and [DETACH] statements also cause
  2922   2972   ** sqlite3_stmt_readonly() to return true since, while those statements
  2923   2973   ** change the configuration of a database connection, they do not make 
  2924   2974   ** changes to the content of the database files on disk.
  2925   2975   */
  2926   2976   int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  2927   2977   
         2978  +/*
         2979  +** CAPI3REF: Determine If A Prepared Statement Has Been Reset
         2980  +**
         2981  +** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
         2982  +** [prepared statement] S has been stepped at least once using 
         2983  +** [sqlite3_step(S)] but has not run to completion and/or has not 
         2984  +** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
         2985  +** interface returns false if S is a NULL pointer.  If S is not a 
         2986  +** NULL pointer and is not a pointer to a valid [prepared statement]
         2987  +** object, then the behavior is undefined and probably undesirable.
         2988  +**
         2989  +** This interface can be used in combination [sqlite3_next_stmt()]
         2990  +** to locate all prepared statements associated with a database 
         2991  +** connection that are in need of being reset.  This can be used,
         2992  +** for example, in diagnostic routines to search for prepared 
         2993  +** statements that are holding a transaction open.
         2994  +*/
         2995  +int sqlite3_stmt_busy(sqlite3_stmt*);
         2996  +
  2928   2997   /*
  2929   2998   ** CAPI3REF: Dynamically Typed Value Object
  2930   2999   ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  2931   3000   **
  2932   3001   ** SQLite uses the sqlite3_value object to represent all values
  2933   3002   ** that can be stored in a database table. SQLite uses dynamic typing
  2934   3003   ** for the values it stores.  ^Values stored in sqlite3_value objects
................................................................................
  3462   3531   ** ^The values returned by [sqlite3_column_bytes()] and 
  3463   3532   ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3464   3533   ** of the string.  ^For clarity: the values returned by
  3465   3534   ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3466   3535   ** bytes in the string, not the number of characters.
  3467   3536   **
  3468   3537   ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3469         -** even empty strings, are always zero terminated.  ^The return
         3538  +** even empty strings, are always zero-terminated.  ^The return
  3470   3539   ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3471   3540   **
  3472   3541   ** ^The object returned by [sqlite3_column_value()] is an
  3473   3542   ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
  3474   3543   ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3475   3544   ** If the [unprotected sqlite3_value] object returned by
  3476   3545   ** [sqlite3_column_value()] is used in any other way, including calls
................................................................................
  4362   4431   ** returned by sqlite3_db_handle is the same [database connection]
  4363   4432   ** that was the first argument
  4364   4433   ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4365   4434   ** create the statement in the first place.
  4366   4435   */
  4367   4436   sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4368   4437   
         4438  +/*
         4439  +** CAPI3REF: Return The Filename For A Database Connection
         4440  +**
         4441  +** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
         4442  +** associated with database N of connection D.  ^The main database file
         4443  +** has the name "main".  If there is no attached database N on the database
         4444  +** connection D, or if database N is a temporary or in-memory database, then
         4445  +** a NULL pointer is returned.
         4446  +**
         4447  +** ^The filename returned by this function is the output of the
         4448  +** xFullPathname method of the [VFS].  ^In other words, the filename
         4449  +** will be an absolute pathname, even if the filename used
         4450  +** to open the database originally was a URI or relative pathname.
         4451  +*/
         4452  +const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
         4453  +
  4369   4454   /*
  4370   4455   ** CAPI3REF: Find the next prepared statement
  4371   4456   **
  4372   4457   ** ^This interface returns a pointer to the next [prepared statement] after
  4373   4458   ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
  4374   4459   ** then this interface returns a pointer to the first prepared statement
  4375   4460   ** associated with the database connection pDb.  ^If no prepared statement
................................................................................
  4397   4482   ** then the commit is converted into a rollback.
  4398   4483   **
  4399   4484   ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4400   4485   ** return the P argument from the previous call of the same function
  4401   4486   ** on the same [database connection] D, or NULL for
  4402   4487   ** the first call for each function on D.
  4403   4488   **
         4489  +** The commit and rollback hook callbacks are not reentrant.
  4404   4490   ** The callback implementation must not do anything that will modify
  4405   4491   ** the database connection that invoked the callback.  Any actions
  4406   4492   ** to modify the database connection must be deferred until after the
  4407   4493   ** completion of the [sqlite3_step()] call that triggered the commit
  4408   4494   ** or rollback hook in the first place.
  4409         -** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4410         -** database connections for the meaning of "modify" in this paragraph.
         4495  +** Note that running any other SQL statements, including SELECT statements,
         4496  +** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
         4497  +** the database connections for the meaning of "modify" in this paragraph.
  4411   4498   **
  4412   4499   ** ^Registering a NULL function disables the callback.
  4413   4500   **
  4414   4501   ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4415   4502   ** operation is allowed to continue normally.  ^If the commit hook
  4416   4503   ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4417   4504   ** ^The rollback hook is invoked on a rollback that results from a commit
................................................................................
  4516   4603   ** of heap memory by deallocating non-essential memory allocations
  4517   4604   ** held by the database library.   Memory used to cache database
  4518   4605   ** pages to improve performance is an example of non-essential memory.
  4519   4606   ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  4520   4607   ** which might be more or less than the amount requested.
  4521   4608   ** ^The sqlite3_release_memory() routine is a no-op returning zero
  4522   4609   ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
         4610  +**
         4611  +** See also: [sqlite3_db_release_memory()]
  4523   4612   */
  4524   4613   int sqlite3_release_memory(int);
  4525   4614   
         4615  +/*
         4616  +** CAPI3REF: Free Memory Used By A Database Connection
         4617  +**
         4618  +** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
         4619  +** memory as possible from database connection D. Unlike the
         4620  +** [sqlite3_release_memory()] interface, this interface is effect even
         4621  +** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
         4622  +** omitted.
         4623  +**
         4624  +** See also: [sqlite3_release_memory()]
         4625  +*/
         4626  +int sqlite3_db_release_memory(sqlite3*);
         4627  +
  4526   4628   /*
  4527   4629   ** CAPI3REF: Impose A Limit On Heap Size
  4528   4630   **
  4529   4631   ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  4530   4632   ** soft limit on the amount of heap memory that may be allocated by SQLite.
  4531   4633   ** ^SQLite strives to keep heap memory utilization below the soft heap
  4532   4634   ** limit by reducing the number of pages held in the page cache
................................................................................
  4533   4635   ** as heap memory usages approaches the limit.
  4534   4636   ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  4535   4637   ** below the limit, it will exceed the limit rather than generate
  4536   4638   ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
  4537   4639   ** is advisory only.
  4538   4640   **
  4539   4641   ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  4540         -** the soft heap limit prior to the call.  ^If the argument N is negative
         4642  +** the soft heap limit prior to the call, or negative in the case of an
         4643  +** error.  ^If the argument N is negative
  4541   4644   ** then no change is made to the soft heap limit.  Hence, the current
  4542   4645   ** size of the soft heap limit can be determined by invoking
  4543   4646   ** sqlite3_soft_heap_limit64() with a negative argument.
  4544   4647   **
  4545   4648   ** ^If the argument N is zero then the soft heap limit is disabled.
  4546   4649   **
  4547   4650   ** ^(The soft heap limit is not enforced in the current implementation
................................................................................
  4549   4652   **
  4550   4653   ** <ul>
  4551   4654   ** <li> The soft heap limit is set to zero.
  4552   4655   ** <li> Memory accounting is disabled using a combination of the
  4553   4656   **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  4554   4657   **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  4555   4658   ** <li> An alternative page cache implementation is specified using
  4556         -**      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
         4659  +**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  4557   4660   ** <li> The page cache allocates from its own memory pool supplied
  4558   4661   **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  4559   4662   **      from the heap.
  4560   4663   ** </ul>)^
  4561   4664   **
  4562   4665   ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  4563   4666   ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
................................................................................
  5291   5394   ** The SQLite source code contains multiple implementations
  5292   5395   ** of these mutex routines.  An appropriate implementation
  5293   5396   ** is selected automatically at compile-time.  ^(The following
  5294   5397   ** implementations are available in the SQLite core:
  5295   5398   **
  5296   5399   ** <ul>
  5297   5400   ** <li>   SQLITE_MUTEX_OS2
  5298         -** <li>   SQLITE_MUTEX_PTHREAD
         5401  +** <li>   SQLITE_MUTEX_PTHREADS
  5299   5402   ** <li>   SQLITE_MUTEX_W32
  5300   5403   ** <li>   SQLITE_MUTEX_NOOP
  5301   5404   ** </ul>)^
  5302   5405   **
  5303   5406   ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5304   5407   ** that does no real locking and is appropriate for use in
  5305   5408   ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
  5306         -** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
         5409  +** SQLITE_MUTEX_PTHREADS, and SQLITE_MUTEX_W32 implementations
  5307   5410   ** are appropriate for use on OS/2, Unix, and Windows.
  5308   5411   **
  5309   5412   ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5310   5413   ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5311   5414   ** implementation is included with the library. In this case the
  5312   5415   ** application must supply a custom mutex implementation using the
  5313   5416   ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
................................................................................
  5489   5592   ** with the SQLITE_DEBUG flag.  ^External mutex implementations
  5490   5593   ** are only required to provide these routines if SQLITE_DEBUG is
  5491   5594   ** defined and if NDEBUG is not defined.
  5492   5595   **
  5493   5596   ** ^These routines should return true if the mutex in their argument
  5494   5597   ** is held or not held, respectively, by the calling thread.
  5495   5598   **
  5496         -** ^The implementation is not required to provided versions of these
         5599  +** ^The implementation is not required to provide versions of these
  5497   5600   ** routines that actually work. If the implementation does not provide working
  5498   5601   ** versions of these routines, it should at least provide stubs that always
  5499   5602   ** return true so that one does not get spurious assertion failures.
  5500   5603   **
  5501   5604   ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  5502   5605   ** the routine should return 1.   This seems counter-intuitive since
  5503   5606   ** clearly the mutex cannot be held if it does not exist.  But
................................................................................
  5617   5720   #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
  5618   5721   #define SQLITE_TESTCTRL_PENDING_BYTE            11
  5619   5722   #define SQLITE_TESTCTRL_ASSERT                  12
  5620   5723   #define SQLITE_TESTCTRL_ALWAYS                  13
  5621   5724   #define SQLITE_TESTCTRL_RESERVE                 14
  5622   5725   #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
  5623   5726   #define SQLITE_TESTCTRL_ISKEYWORD               16
  5624         -#define SQLITE_TESTCTRL_PGHDRSZ                 17
  5625         -#define SQLITE_TESTCTRL_SCRATCHMALLOC           18
  5626         -#define SQLITE_TESTCTRL_LOCALTIME_FAULT         19
         5727  +#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
         5728  +#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
         5729  +#define SQLITE_TESTCTRL_EXPLAIN_STMT            19
  5627   5730   #define SQLITE_TESTCTRL_LAST                    19
  5628   5731   
  5629   5732   /*
  5630   5733   ** CAPI3REF: SQLite Runtime Status
  5631   5734   **
  5632   5735   ** ^This interface is used to retrieve runtime status information
  5633   5736   ** about the performance of SQLite, and optionally to reset various
................................................................................
  5922   6025   **
  5923   6026   ** The sqlite3_pcache type is opaque.  It is implemented by
  5924   6027   ** the pluggable module.  The SQLite core has no knowledge of
  5925   6028   ** its size or internal structure and never deals with the
  5926   6029   ** sqlite3_pcache object except by holding and passing pointers
  5927   6030   ** to the object.
  5928   6031   **
  5929         -** See [sqlite3_pcache_methods] for additional information.
         6032  +** See [sqlite3_pcache_methods2] for additional information.
  5930   6033   */
  5931   6034   typedef struct sqlite3_pcache sqlite3_pcache;
         6035  +
         6036  +/*
         6037  +** CAPI3REF: Custom Page Cache Object
         6038  +**
         6039  +** The sqlite3_pcache_page object represents a single page in the
         6040  +** page cache.  The page cache will allocate instances of this
         6041  +** object.  Various methods of the page cache use pointers to instances
         6042  +** of this object as parameters or as their return value.
         6043  +**
         6044  +** See [sqlite3_pcache_methods2] for additional information.
         6045  +*/
         6046  +typedef struct sqlite3_pcache_page sqlite3_pcache_page;
         6047  +struct sqlite3_pcache_page {
         6048  +  void *pBuf;        /* The content of the page */
         6049  +  void *pExtra;      /* Extra information associated with the page */
         6050  +};
  5932   6051   
  5933   6052   /*
  5934   6053   ** CAPI3REF: Application Defined Page Cache.
  5935   6054   ** KEYWORDS: {page cache}
  5936   6055   **
  5937         -** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
         6056  +** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  5938   6057   ** register an alternative page cache implementation by passing in an 
  5939         -** instance of the sqlite3_pcache_methods structure.)^
         6058  +** instance of the sqlite3_pcache_methods2 structure.)^
  5940   6059   ** In many applications, most of the heap memory allocated by 
  5941   6060   ** SQLite is used for the page cache.
  5942   6061   ** By implementing a 
  5943   6062   ** custom page cache using this API, an application can better control
  5944   6063   ** the amount of memory consumed by SQLite, the way in which 
  5945   6064   ** that memory is allocated and released, and the policies used to 
  5946   6065   ** determine exactly which parts of a database file are cached and for 
  5947   6066   ** how long.
  5948   6067   **
  5949   6068   ** The alternative page cache mechanism is an
  5950   6069   ** extreme measure that is only needed by the most demanding applications.
  5951   6070   ** The built-in page cache is recommended for most uses.
  5952   6071   **
  5953         -** ^(The contents of the sqlite3_pcache_methods structure are copied to an
         6072  +** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  5954   6073   ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
  5955   6074   ** the application may discard the parameter after the call to
  5956   6075   ** [sqlite3_config()] returns.)^
  5957   6076   **
  5958   6077   ** [[the xInit() page cache method]]
  5959   6078   ** ^(The xInit() method is called once for each effective 
  5960   6079   ** call to [sqlite3_initialize()])^
  5961   6080   ** (usually only once during the lifetime of the process). ^(The xInit()
  5962         -** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
         6081  +** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  5963   6082   ** The intent of the xInit() method is to set up global data structures 
  5964   6083   ** required by the custom page cache implementation. 
  5965   6084   ** ^(If the xInit() method is NULL, then the 
  5966   6085   ** built-in default page cache is used instead of the application defined
  5967   6086   ** page cache.)^
  5968   6087   **
  5969   6088   ** [[the xShutdown() page cache method]]
................................................................................
  5982   6101   ** call to xShutdown().
  5983   6102   **
  5984   6103   ** [[the xCreate() page cache methods]]
  5985   6104   ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  5986   6105   ** SQLite will typically create one cache instance for each open database file,
  5987   6106   ** though this is not guaranteed. ^The
  5988   6107   ** first parameter, szPage, is the size in bytes of the pages that must
  5989         -** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
  5990         -** will the page size of the database file that is to be cached plus an
  5991         -** increment (here called "R") of less than 250.  SQLite will use the
  5992         -** extra R bytes on each page to store metadata about the underlying
  5993         -** database page on disk.  The value of R depends
         6108  +** be allocated by the cache.  ^szPage will always a power of two.  ^The
         6109  +** second parameter szExtra is a number of bytes of extra storage 
         6110  +** associated with each page cache entry.  ^The szExtra parameter will
         6111  +** a number less than 250.  SQLite will use the
         6112  +** extra szExtra bytes on each page to store metadata about the underlying
         6113  +** database page on disk.  The value passed into szExtra depends
  5994   6114   ** on the SQLite version, the target platform, and how SQLite was compiled.
  5995         -** ^(R is constant for a particular build of SQLite. Except, there are two
  5996         -** distinct values of R when SQLite is compiled with the proprietary
  5997         -** ZIPVFS extension.)^  ^The second argument to
  5998         -** xCreate(), bPurgeable, is true if the cache being created will
  5999         -** be used to cache database pages of a file stored on disk, or
         6115  +** ^The third argument to xCreate(), bPurgeable, is true if the cache being
         6116  +** created will be used to cache database pages of a file stored on disk, or
  6000   6117   ** false if it is used for an in-memory database. The cache implementation
  6001   6118   ** does not have to do anything special based with the value of bPurgeable;
  6002   6119   ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
  6003   6120   ** never invoke xUnpin() except to deliberately delete a page.
  6004   6121   ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6005   6122   ** false will always have the "discard" flag set to true.  
  6006   6123   ** ^Hence, a cache created with bPurgeable false will
................................................................................
  6016   6133   **
  6017   6134   ** [[the xPagecount() page cache methods]]
  6018   6135   ** The xPagecount() method must return the number of pages currently
  6019   6136   ** stored in the cache, both pinned and unpinned.
  6020   6137   ** 
  6021   6138   ** [[the xFetch() page cache methods]]
  6022   6139   ** The xFetch() method locates a page in the cache and returns a pointer to 
  6023         -** the page, or a NULL pointer.
  6024         -** A "page", in this context, means a buffer of szPage bytes aligned at an
  6025         -** 8-byte boundary. The page to be fetched is determined by the key. ^The
  6026         -** minimum key value is 1.  After it has been retrieved using xFetch, the page 
  6027         -** is considered to be "pinned".
         6140  +** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
         6141  +** The pBuf element of the returned sqlite3_pcache_page object will be a
         6142  +** pointer to a buffer of szPage bytes used to store the content of a 
         6143  +** single database page.  The pExtra element of sqlite3_pcache_page will be
         6144  +** a pointer to the szExtra bytes of extra storage that SQLite has requested
         6145  +** for each entry in the page cache.
         6146  +**
         6147  +** The page to be fetched is determined by the key. ^The minimum key value
         6148  +** is 1.  After it has been retrieved using xFetch, the page is considered
         6149  +** to be "pinned".
  6028   6150   **
  6029   6151   ** If the requested page is already in the page cache, then the page cache
  6030   6152   ** implementation must return a pointer to the page buffer with its content
  6031   6153   ** intact.  If the requested page is not already in the cache, then the
  6032   6154   ** cache implementation should use the value of the createFlag
  6033   6155   ** parameter to help it determined what action to take:
  6034   6156   **
................................................................................
  6073   6195   ** of these pages are pinned, they are implicitly unpinned, meaning that
  6074   6196   ** they can be safely discarded.
  6075   6197   **
  6076   6198   ** [[the xDestroy() page cache method]]
  6077   6199   ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6078   6200   ** All resources associated with the specified cache should be freed. ^After
  6079   6201   ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6080         -** handle invalid, and will not use it with any other sqlite3_pcache_methods
         6202  +** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6081   6203   ** functions.
         6204  +**
         6205  +** [[the xShrink() page cache method]]
         6206  +** ^SQLite invokes the xShrink() method when it wants the page cache to
         6207  +** free up as much of heap memory as possible.  The page cache implementation
         6208  +** is not obligated to free any memory, but well-behaved implementions should
         6209  +** do their best.
         6210  +*/
         6211  +typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
         6212  +struct sqlite3_pcache_methods2 {
         6213  +  int iVersion;
         6214  +  void *pArg;
         6215  +  int (*xInit)(void*);
         6216  +  void (*xShutdown)(void*);
         6217  +  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
         6218  +  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
         6219  +  int (*xPagecount)(sqlite3_pcache*);
         6220  +  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
         6221  +  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
         6222  +  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
         6223  +      unsigned oldKey, unsigned newKey);
         6224  +  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
         6225  +  void (*xDestroy)(sqlite3_pcache*);
         6226  +  void (*xShrink)(sqlite3_pcache*);
         6227  +};
         6228  +
         6229  +/*
         6230  +** This is the obsolete pcache_methods object that has now been replaced
         6231  +** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
         6232  +** retained in the header file for backwards compatibility only.
  6082   6233   */
  6083   6234   typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6084   6235   struct sqlite3_pcache_methods {
  6085   6236     void *pArg;
  6086   6237     int (*xInit)(void*);
  6087   6238     void (*xShutdown)(void*);
  6088   6239     sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
................................................................................
  6090   6241     int (*xPagecount)(sqlite3_pcache*);
  6091   6242     void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6092   6243     void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6093   6244     void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6094   6245     void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6095   6246     void (*xDestroy)(sqlite3_pcache*);
  6096   6247   };
         6248  +
  6097   6249   
  6098   6250   /*
  6099   6251   ** CAPI3REF: Online Backup Object
  6100   6252   **
  6101   6253   ** The sqlite3_backup object records state information about an ongoing
  6102   6254   ** online backup operation.  ^The sqlite3_backup object is created by
  6103   6255   ** a call to [sqlite3_backup_init()] and is destroyed by a call to

Changes to src/sqliteInt.h.

   121    121   #if defined(THREADSAFE)
   122    122   # define SQLITE_THREADSAFE THREADSAFE
   123    123   #else
   124    124   # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
   125    125   #endif
   126    126   #endif
   127    127   
          128  +/*
          129  +** Powersafe overwrite is on by default.  But can be turned off using
          130  +** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
          131  +*/
          132  +#ifndef SQLITE_POWERSAFE_OVERWRITE
          133  +# define SQLITE_POWERSAFE_OVERWRITE 1
          134  +#endif
          135  +
   128    136   /*
   129    137   ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
   130    138   ** It determines whether or not the features related to 
   131    139   ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
   132    140   ** be overridden at runtime using the sqlite3_config() API.
   133    141   */
   134    142   #if !defined(SQLITE_DEFAULT_MEMSTATUS)
................................................................................
   342    350  <