/ Check-in [7f51ad97]
Login

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

Overview
Comment:Merge the performance enhancements of trunk (and some obscure bug fixes) into the sessions branch.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sessions
Files: files | file ages | folders
SHA1: 7f51ad97f0b24c57453d58faf25eee68861faa23
User & Date: drh 2014-03-04 14:34:14
Context
2014-03-05
14:49
Merge in various obscure bug fixes and the removal of Mem.memType from trunk. check-in: 0828975d user: drh tags: sessions
2014-03-04
14:34
Merge the performance enhancements of trunk (and some obscure bug fixes) into the sessions branch. check-in: 7f51ad97 user: drh tags: sessions
13:18
Improve clarity of presentation in the sqlite3VdbeMemFromBtree() routine. check-in: 9830c343 user: drh tags: trunk
2014-02-11
16:31
Sync with trunk. Bring in the command-line shell updates and the new 3.8.4 version number. check-in: 2cd35ff6 user: drh tags: sessions
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to Makefile.msc.

   210    210   NLTLIBPATHS = "/LIBPATH:$(NCRTLIBPATH)" "/LIBPATH:$(NSDKLIBPATH)"
   211    211   !ENDIF
   212    212   
   213    213   # C compiler and options for use in building executables that
   214    214   # will run on the target platform.  (BCC and TCC are usually the
   215    215   # same unless your are cross-compiling.)
   216    216   #
   217         -TCC = $(CC) -W3 -DSQLITE_OS_WIN=1 -I$(TOP) -I$(TOP)\src -fp:precise
          217  +TCC = $(CC) -W3 -DSQLITE_OS_WIN=1 -I. -I$(TOP) -I$(TOP)\src -fp:precise
   218    218   RCC = $(RC) -DSQLITE_OS_WIN=1 -I$(TOP) -I$(TOP)\src
   219    219   
   220    220   # Check if assembly code listings should be generated for the source
   221    221   # code files to be compiled.
   222    222   #
   223    223   !IF $(USE_LISTINGS)!=0
   224    224   TCC = $(TCC) -FAcs
................................................................................
  1235   1235   	del /Q parse.y parse.h parse.h.temp
  1236   1236   	copy $(TOP)\src\parse.y .
  1237   1237   	.\lemon.exe $(OPT_FEATURE_FLAGS) $(OPTS) parse.y
  1238   1238   	move parse.h parse.h.temp
  1239   1239   	$(NAWK) -f $(TOP)\addopcodes.awk parse.h.temp > parse.h
  1240   1240   
  1241   1241   sqlite3.h:	$(TOP)\src\sqlite.h.in $(TOP)\manifest.uuid $(TOP)\VERSION
  1242         -	$(TCLSH_CMD) $(TOP)\tool\mksqlite3h.tcl $(TOP) > sqlite3.h
         1242  +	$(TCLSH_CMD) $(TOP)\tool\mksqlite3h.tcl $(TOP:\=/) > sqlite3.h
  1243   1243   
  1244   1244   mkkeywordhash.exe:	$(TOP)\tool\mkkeywordhash.c
  1245   1245   	$(BCC) -Fe$@ $(OPT_FEATURE_FLAGS) $(OPTS) $(TOP)\tool\mkkeywordhash.c /link $(NLTLIBPATHS)
  1246   1246   
  1247   1247   keywordhash.h:	$(TOP)\tool\mkkeywordhash.c mkkeywordhash.exe
  1248   1248   	.\mkkeywordhash.exe > keywordhash.h
  1249   1249   
................................................................................
  1338   1338   
  1339   1339   testfixture.exe:	$(TESTFIXTURE_SRC) $(LIBRESOBJS) $(HDR)
  1340   1340   	$(LTLINK) -DSQLITE_NO_SYNC=1 $(TESTFIXTURE_FLAGS) \
  1341   1341   		-DBUILD_sqlite -I$(TCLINCDIR) \
  1342   1342   		$(TESTFIXTURE_SRC) \
  1343   1343   		/link $(LTLINKOPTS) $(LTLIBPATHS) $(LIBRESOBJS) $(LTLIBS) $(TLIBS)
  1344   1344   
         1345  +extensiontest: testfixture.exe testloadext.dll
         1346  +	.\testfixture.exe $(TOP)\test\loadext.test
         1347  +
  1345   1348   fulltest:	testfixture.exe sqlite3.exe
  1346   1349   	.\testfixture.exe $(TOP)\test\all.test
  1347   1350   
  1348   1351   soaktest:	testfixture.exe sqlite3.exe
  1349   1352   	.\testfixture.exe $(TOP)\test\all.test -soak=1
  1350   1353   
  1351   1354   fulltestonly:	testfixture.exe sqlite3.exe
................................................................................
  1364   1367   	$(NAWK) -f $(TOP)\tool\tostr.awk $(TOP)\tool\spaceanal.tcl >> $@
  1365   1368   	echo ; return zMainloop; } >> $@
  1366   1369   
  1367   1370   sqlite3_analyzer.exe:	sqlite3_analyzer.c $(LIBRESOBJS)
  1368   1371   	$(LTLINK) -DBUILD_sqlite -DTCLSH=2 -I$(TCLINCDIR) sqlite3_analyzer.c \
  1369   1372   		/link $(LTLINKOPTS) $(LTLIBPATHS) $(LIBRESOBJS) $(LTLIBS) $(TLIBS)
  1370   1373   
         1374  +testloadext.lo:	$(TOP)\src\test_loadext.c
         1375  +	$(LTCOMPILE) -c $(TOP)\src\test_loadext.c
         1376  +
         1377  +testloadext.dll: testloadext.lo
         1378  +	$(LD) $(LDFLAGS) $(LTLINKOPTS) $(LTLIBPATHS) /DLL /OUT:$@ testloadext.lo
         1379  +
  1371   1380   showdb.exe:	$(TOP)\tool\showdb.c $(SQLITE3C)
  1372   1381   	$(LTLINK) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -Fe$@ \
  1373   1382   		$(TOP)\tool\showdb.c $(SQLITE3C)
  1374   1383   
  1375   1384   wordcount.exe:	$(TOP)\test\wordcount.c $(SQLITE3C)
  1376   1385   	$(LTLINK) -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION -Fe$@ \
  1377   1386   		$(TOP)\test\wordcount.c $(SQLITE3C)
................................................................................
  1382   1391   
  1383   1392   clean:
  1384   1393   	del /Q *.lo *.ilk *.lib *.obj *.pdb sqlite3.exe libsqlite3.lib
  1385   1394   	del /Q *.cod *.da *.bb *.bbg gmon.out
  1386   1395   	del /Q sqlite3.h opcodes.c opcodes.h
  1387   1396   	del /Q lemon.exe lempar.c parse.*
  1388   1397   	del /Q mkkeywordhash.exe keywordhash.h
         1398  +	del /Q notasharedlib.*
  1389   1399   	-rmdir /Q/S .deps
  1390   1400   	-rmdir /Q/S .libs
  1391   1401   	-rmdir /Q/S quota2a
  1392   1402   	-rmdir /Q/S quota2b
  1393   1403   	-rmdir /Q/S quota2c
  1394   1404   	-rmdir /Q/S tsrc
  1395   1405   	del /Q .target_source
  1396   1406   	del /Q tclsqlite3.exe tclsqlite3.exp
         1407  +	del /Q testloadext.dll testloadext.exp
  1397   1408   	del /Q testfixture.exe testfixture.exp test.db
  1398   1409   	del /Q sqlite3.dll sqlite3.lib sqlite3.exp sqlite3.def
  1399   1410   	del /Q sqlite3.c sqlite3-*.c
  1400   1411   	del /Q sqlite3rc.h
  1401   1412   	del /Q shell.c sqlite3ext.h
  1402   1413   	del /Q sqlite3_analyzer.exe sqlite3_analyzer.exp sqlite3_analyzer.c
  1403   1414   	del /Q sqlite-*-output.vsix

Name change from README to README.md.

     1         -This directory contains source code to 
            1  +<h1 align="center">SQLite Source Repository</h1>
     2      2   
     3         -    SQLite: An Embeddable SQL Database Engine
            3  +This repository contains the complete source code for the SQLite database
            4  +engine.  Some test scripts are also include.  However, many other test scripts
            5  +and most of the documentation are managed separately.
     4      6   
     5         -To compile the project, first create a directory in which to place
            7  +## Compiling
            8  +
            9  +First create a directory in which to place
     6     10   the build products.  It is recommended, but not required, that the
     7     11   build directory be separate from the source directory.  Cd into the
     8     12   build directory and then from the build directory run the configure
     9     13   script found at the root of the source tree.  Then run "make".
    10     14   
    11     15   For example:
    12     16   
    13     17       tar xzf sqlite.tar.gz    ;#  Unpack the source tree into "sqlite"
    14     18       mkdir bld                ;#  Build will occur in a sibling directory
    15     19       cd bld                   ;#  Change to the build directory
    16     20       ../sqlite/configure      ;#  Run the configure script
    17     21       make                     ;#  Run the makefile.
    18         -    make install             ;#  (Optional) Install the build products
           22  +    make sqlite3.c           ;#  Build the "amalgamation" source file
           23  +    make test                ;#  Run some tests (requires Tcl)
           24  +
           25  +See the makefile for additional targets.
    19     26   
    20     27   The configure script uses autoconf 2.61 and libtool.  If the configure
    21     28   script does not work out for you, there is a generic makefile named
    22     29   "Makefile.linux-gcc" in the top directory of the source tree that you
    23     30   can copy and edit to suit your needs.  Comments on the generic makefile
    24     31   show what changes are needed.
    25     32   
    26         -The linux binaries on the website are created using the generic makefile,
    27         -not the configure script.  The windows binaries on the website are created
    28         -using MinGW32 configured as a cross-compiler running under Linux.  For 
    29         -details, see the ./publish.sh script at the top-level of the source tree.
    30         -The developers do not use teh configure script.
           33  +## Using MSVC
           34  +
           35  +On Windows, all applicable build products can be compiled with MSVC.
           36  +First open the command prompt window associated with the desired compiler
           37  +version (e.g. "Developer Command Prompt for VS2013").  Next, use NMAKE
           38  +with the provided "Makefile.msc" to build one of the supported targets.
           39  +
           40  +For example:
           41  +
           42  +    mkdir bld
           43  +    cd bld
           44  +    nmake /f Makefile.msc TOP=..\sqlite
           45  +    nmake /f Makefile.msc sqlite3.c TOP=..\sqlite
           46  +    nmake /f Makefile.msc sqlite3.dll TOP=..\sqlite
           47  +    nmake /f Makefile.msc sqlite3.exe TOP=..\sqlite
           48  +    nmake /f Makefile.msc test TOP=..\sqlite
           49  +
           50  +There are several build options that can be set via the NMAKE command
           51  +line.  For example, to build for WinRT, simply add "FOR_WINRT=1" argument
           52  +to the "sqlite3.dll" command line above.  When debugging into the SQLite
           53  +code, adding the "DEBUG=1" argument to one of the above command lines is
           54  +recommended.
           55  +
           56  +SQLite does not require Tcl to run, but a Tcl installation is required
           57  +by the makefiles (including those for MSVC).  SQLite contains a lot of
           58  +generated code and Tcl is used to do much of that code generation.  The
           59  +makefiles also require AWK.
           60  +
           61  +## Source Code Tour
           62  +
           63  +Most of the core source files are in the **src/** subdirectory.  But
           64  +src/ also contains files used to build the "testfixture" test harness;
           65  +those file all begin with "test".  And src/ contains the "shell.c" file
           66  +which is the main program for the "sqlite3.exe" command-line shell and
           67  +the "tclsqlite.c" file which implements the bindings to SQLite from the
           68  +Tcl programming language.  (Historical note:  SQLite began as a Tcl
           69  +extension and only later escaped to the wild as an independent library.)
           70  +
           71  +Test scripts and programs are found in the **test/** subdirectory.
           72  +There are other test suites for SQLite (see
           73  +[How SQLite Is Tested](http://www.sqlite.org/testing.html))
           74  +but those other test suites are
           75  +in separate source repositories.
           76  +
           77  +The **ext/** subdirectory contains code for extensions.  The
           78  +Full-text search engine is in **ext/fts3**.  The R-Tree engine is in
           79  +**ext/rtree**.  The **ext/misc** subdirectory contains a number of
           80  +smaller, single-file extensions, such as a REGEXP operator.
           81  +
           82  +The **tool/** subdirectory contains various scripts and programs used
           83  +for building generated source code files or for testing or for generating
           84  +accessory programs such as "sqlite3_analyzer(.exe)".
           85  +
           86  +### Generated Source Code Files
           87  +
           88  +Several of the C-language source files used by SQLite are generated from
           89  +other sources rather than being typed in manually by a programmer.  This
           90  +section will summarize those automatically-generated files.  To create all
           91  +of the automatically-generated files, simply run "make target&#95;source".
           92  +The "target&#95;source" make target will create a subdirectory "tsrc/" and
           93  +fill it with all the source files needed to build SQLite, both
           94  +manually-edited files and automatically-generated files.
           95  +
           96  +The SQLite interface is defined by the **sqlite3.h** header file, which is
           97  +generated from src/sqlite.h.in, ./manifest.uuid, and ./VERSION.  The
           98  +Tcl script at tool/mksqlite3h.tcl does the conversion.  The manifest.uuid
           99  +file contains the SHA1 hash of the particular check-in and is used to generate
          100  +the SQLITE_SOURCE_ID macro.  The VERSION file contains the current SQLite
          101  +version number.  The sqlite3.h header is really just a copy of src/sqlite.h.in
          102  +with the source-id and version number inserted at just the right spots.
          103  +Note that comment text in the sqlite3.h file is used to generate much of
          104  +the SQLite API documentation.  The Tcl scripts used to generate that
          105  +documentation are in a separate source repository.
          106  +
          107  +The SQL language parser is **parse.c** which is generate from a grammar in
          108  +the src/parse.y file.  The conversion of "parse.y" into "parse.c" is done
          109  +by the [lemon](./doc/lemon.html) LALR(1) parser generator.  The source code
          110  +for lemon is at tool/lemon.c.  Lemon uses a
          111  +template for generating its parser.  A generic template is in tool/lempar.c,
          112  +but SQLite uses a slightly modified template found in src/lempar.c.
          113  +
          114  +Lemon also generates the **parse.h** header file, at the same time it
          115  +generates parse.c. But the parse.h header file is
          116  +modified further (to add additional symbols) using the ./addopcodes.awk
          117  +AWK script.
          118  +
          119  +The **opcodes.h** header file contains macros that define the numbers
          120  +corresponding to opcodes in the "VDBE" virtual machine.  The opcodes.h
          121  +file is generated by the scanning the src/vdbe.c source file.  The
          122  +AWK script at ./mkopcodeh.awk does this scan and generates opcodes.h.
          123  +A second AWK script, ./mkopcodec.awk, then scans opcodes.h to generate
          124  +the **opcodes.c** source file, which contains a reverse mapping from
          125  +opcode-number to opcode-name that is used for EXPLAIN output.
          126  +
          127  +The **keywordhash.h** header file contains the definition of a hash table
          128  +that maps SQL language keywords (ex: "CREATE", "SELECT", "INDEX", etc.) into
          129  +the numeric codes used by the parse.c parser.  The keywordhash.h file is
          130  +generated by a C-language program at tool mkkeywordhash.c.
          131  +
          132  +### The Amalgamation
          133  +
          134  +All of the individual C source code and header files (both manually-edited
          135  +and automatically-generated) can be combined into a single big source file
          136  +**sqlite3.c** called "the amalgamation".  The amalgamation is the recommended
          137  +way of using SQLite in a larger application.  Combining all individual
          138  +source code files into a single big source code file allows the C compiler
          139  +to perform more cross-procedure analysis and generate better code.  SQLite
          140  +runs about 5% faster when compiled from the amalgamation versus when compiled
          141  +from individual source files.
          142  +
          143  +The amalgamation is generated from the tool/mksqlite3c.tcl Tcl script.
          144  +First, all of the individual source files must be gathered into the tsrc/
          145  +subdirectory (using the equivalent of "make target_source") then the
          146  +tool/mksqlite3c.tcl script is run to copy them all together in just the
          147  +right order while resolving internal "#include" references.
          148  +
          149  +The amalgamation source file is more than 100K lines long.  Some symbolic
          150  +debuggers (most notably MSVC) are unable to deal with files longer than 64K
          151  +lines.  To work around this, a separate Tcl script, tool/split-sqlite3c.tcl,
          152  +can be run on the amalgamation to break it up into a single small C file
          153  +called **sqlite3-all.c** that does #include on about five other files
          154  +named **sqlite3-1.c**, **sqlite3-2.c**, ..., **sqlite3-5.c**.  In this way,
          155  +all of the source code is contained within a single translation unit so
          156  +that the compiler can do extra cross-procedure optimization, but no
          157  +individual source file exceeds 32K lines in length.
          158  +
          159  +## How It All Fits Together
          160  +
          161  +SQLite is modular in design.
          162  +See the [architectural description](http://www.sqlite.org/arch.html)
          163  +for details. Other documents that are useful in
          164  +(helping to understand how SQLite works include the
          165  +[file format](http://www.sqlite.org/fileformat2.html) description,
          166  +the [virtual machine](http://www.sqlite.org/vdbe.html) that runs
          167  +prepared statements, the description of
          168  +[how transactions work](http://www.sqlite.org/atomiccommit.html), and
          169  +the [overview of the query planner](http://www.sqlite.org/optoverview.html).
          170  +
          171  +Unfortunately, years of effort have gone into optimizating SQLite, both
          172  +for small size and high performance.  And optimizations tend to result in
          173  +complex code.  So there is a lot of complexity in the SQLite implementation.
          174  +
          175  +Key files:
          176  +
          177  +  *  **sqlite3.h** - This file defines the public interface to the SQLite
          178  +     library.  Readers will need to be familiar with this interface before
          179  +     trying to understand how the library works internally.
          180  +
          181  +  *  **sqliteInt.h** - this header file defines many of the data objects
          182  +     used internally by SQLite.
          183  +
          184  +  *  **parse.y** - This file describes the LALR(1) grammer that SQLite uses
          185  +     to parse SQL statements, and the actions that are taken at each stop
          186  +     in the parsing process.
          187  +
          188  +  *  **vdbe.c** - This file implements the virtual machine that runs
          189  +     prepared statements.  There are various helper files whose names
          190  +     begin with "vdbe".  The VDBE has access to the vdbeInt.h header file
          191  +     which defines internal data objects.  The rest of SQLite interacts
          192  +     with the VDBE through an interface defined by vdbe.h.
          193  +
          194  +  *  **where.c** - This file analyzes the WHERE clause and generates
          195  +     virtual machine code to run queries efficiently.  This file is
          196  +     sometimes called the "query optimizer".  It has its own private
          197  +     header file, whereInt.h, that defines data objects used internally.
          198  +
          199  +  *  **btree.c** - This file contains the implementation of the B-Tree
          200  +     storage engine used by SQLite.
          201  +
          202  +  *  **pager.c** - This file contains the "pager" implementation, the
          203  +     module that implements transactions.
          204  +
          205  +  *  **os_unix.c** and **os_win.c** - These two files implement the interface
          206  +     between SQLite and the underlying operating system using the run-time
          207  +     pluggable VFS interface.
          208  +
    31    209   
    32         -SQLite does not require TCL to run, but a TCL installation is required
    33         -by the makefiles.  SQLite contains a lot of generated code and TCL is
    34         -used to do much of that code generation.  The makefile also requires
    35         -AWK.
          210  +## Contacts
    36    211   
    37         -Contacts:
    38         -
    39         -   http://www.sqlite.org/
          212  +The main SQLite webpage is [http://www.sqlite.org/](http://www.sqlite.org/)
          213  +with geographically distributed backup servers at
          214  +[http://www2.sqlite.org/](http://www2.sqlite.org) and
          215  +[http://www3.sqlite.org/](http://www3.sqlite.org).

Changes to autoconf/tea/tclconfig/install-sh.

     1      1   #!/bin/sh
     2         -
     3         -#
     4      2   # install - install a program, script, or datafile
     5         -# This comes from X11R5; it is not part of GNU.
            3  +
            4  +scriptversion=2011-04-20.01; # UTC
            5  +
            6  +# This originates from X11R5 (mit/util/scripts/install.sh), which was
            7  +# later released in X11R6 (xc/config/util/install.sh) with the
            8  +# following copyright and license.
            9  +#
           10  +# Copyright (C) 1994 X Consortium
           11  +#
           12  +# Permission is hereby granted, free of charge, to any person obtaining a copy
           13  +# of this software and associated documentation files (the "Software"), to
           14  +# deal in the Software without restriction, including without limitation the
           15  +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
           16  +# sell copies of the Software, and to permit persons to whom the Software is
           17  +# furnished to do so, subject to the following conditions:
           18  +#
           19  +# The above copyright notice and this permission notice shall be included in
           20  +# all copies or substantial portions of the Software.
           21  +#
           22  +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
           23  +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
           24  +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
           25  +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
           26  +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC-
           27  +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
           28  +#
           29  +# Except as contained in this notice, the name of the X Consortium shall not
           30  +# be used in advertising or otherwise to promote the sale, use or other deal-
           31  +# ings in this Software without prior written authorization from the X Consor-
           32  +# tium.
           33  +#
           34  +#
           35  +# FSF changes to this file are in the public domain.
     6     36   #
     7         -# $XConsortium: install.sh,v 1.2 89/12/18 14:47:22 jim Exp $
           37  +# Calling this script install-sh is preferred over install.sh, to prevent
           38  +# `make' implicit rules from creating a file called install from it
           39  +# when there is no Makefile.
     8     40   #
     9     41   # This script is compatible with the BSD install script, but was written
    10     42   # from scratch.
    11         -#
    12     43   
           44  +nl='
           45  +'
           46  +IFS=" ""	$nl"
    13     47   
    14     48   # set DOITPROG to echo to test this script
    15     49   
    16     50   # Don't use :- since 4.3BSD and earlier shells don't like it.
    17         -doit="${DOITPROG-}"
    18         -
    19         -
    20         -# put in absolute paths if you don't have them in your path; or use env. vars.
    21         -
    22         -mvprog="${MVPROG-mv}"
    23         -cpprog="${CPPROG-cp}"
    24         -chmodprog="${CHMODPROG-chmod}"
    25         -chownprog="${CHOWNPROG-chown}"
    26         -chgrpprog="${CHGRPPROG-chgrp}"
    27         -stripprog="${STRIPPROG-strip}"
    28         -rmprog="${RMPROG-rm}"
    29         -
    30         -instcmd="$mvprog"
    31         -chmodcmd=""
    32         -chowncmd=""
    33         -chgrpcmd=""
    34         -stripcmd=""
           51  +doit=${DOITPROG-}
           52  +if test -z "$doit"; then
           53  +  doit_exec=exec
           54  +else
           55  +  doit_exec=$doit
           56  +fi
           57  +
           58  +# Put in absolute file names if you don't have them in your path;
           59  +# or use environment vars.
           60  +
           61  +chgrpprog=${CHGRPPROG-chgrp}
           62  +chmodprog=${CHMODPROG-chmod}
           63  +chownprog=${CHOWNPROG-chown}
           64  +cmpprog=${CMPPROG-cmp}
           65  +cpprog=${CPPROG-cp}
           66  +mkdirprog=${MKDIRPROG-mkdir}
           67  +mvprog=${MVPROG-mv}
           68  +rmprog=${RMPROG-rm}
           69  +stripprog=${STRIPPROG-strip}
           70  +
           71  +posix_glob='?'
           72  +initialize_posix_glob='
           73  +  test "$posix_glob" != "?" || {
           74  +    if (set -f) 2>/dev/null; then
           75  +      posix_glob=
           76  +    else
           77  +      posix_glob=:
           78  +    fi
           79  +  }
           80  +'
           81  +
           82  +posix_mkdir=
           83  +
           84  +# Desired mode of installed file.
           85  +mode=0755
           86  +
           87  +chgrpcmd=
           88  +chmodcmd=$chmodprog
           89  +chowncmd=
           90  +mvcmd=$mvprog
    35     91   rmcmd="$rmprog -f"
    36         -mvcmd="$mvprog"
    37         -src=""
    38         -dst=""
    39         -
    40         -while [ x"$1" != x ]; do
    41         -    case $1 in
    42         -	-c) instcmd="$cpprog"
    43         -	    shift
    44         -	    continue;;
    45         -
    46         -	-m) chmodcmd="$chmodprog $2"
    47         -	    shift
    48         -	    shift
    49         -	    continue;;
    50         -
    51         -	-o) chowncmd="$chownprog $2"
    52         -	    shift
    53         -	    shift
    54         -	    continue;;
    55         -
    56         -	-g) chgrpcmd="$chgrpprog $2"
    57         -	    shift
    58         -	    shift
    59         -	    continue;;
    60         -
    61         -	-s) stripcmd="$stripprog"
    62         -	    shift
    63         -	    continue;;
    64         -
    65         -	*)  if [ x"$src" = x ]
    66         -	    then
    67         -		src=$1
    68         -	    else
    69         -		dst=$1
    70         -	    fi
    71         -	    shift
    72         -	    continue;;
    73         -    esac
           92  +stripcmd=
           93  +
           94  +src=
           95  +dst=
           96  +dir_arg=
           97  +dst_arg=
           98  +
           99  +copy_on_change=false
          100  +no_target_directory=
          101  +
          102  +usage="\
          103  +Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE
          104  +   or: $0 [OPTION]... SRCFILES... DIRECTORY
          105  +   or: $0 [OPTION]... -t DIRECTORY SRCFILES...
          106  +   or: $0 [OPTION]... -d DIRECTORIES...
          107  +
          108  +In the 1st form, copy SRCFILE to DSTFILE.
          109  +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY.
          110  +In the 4th, create DIRECTORIES.
          111  +
          112  +Options:
          113  +     --help     display this help and exit.
          114  +     --version  display version info and exit.
          115  +
          116  +  -c            (ignored)
          117  +  -C            install only if different (preserve the last data modification time)
          118  +  -d            create directories instead of installing files.
          119  +  -g GROUP      $chgrpprog installed files to GROUP.
          120  +  -m MODE       $chmodprog installed files to MODE.
          121  +  -o USER       $chownprog installed files to USER.
          122  +  -s            $stripprog installed files.
          123  +  -S            $stripprog installed files.
          124  +  -t DIRECTORY  install into DIRECTORY.
          125  +  -T            report an error if DSTFILE is a directory.
          126  +
          127  +Environment variables override the default commands:
          128  +  CHGRPPROG CHMODPROG CHOWNPROG CMPPROG CPPROG MKDIRPROG MVPROG
          129  +  RMPROG STRIPPROG
          130  +"
          131  +
          132  +while test $# -ne 0; do
          133  +  case $1 in
          134  +    -c) ;;
          135  +
          136  +    -C) copy_on_change=true;;
          137  +
          138  +    -d) dir_arg=true;;
          139  +
          140  +    -g) chgrpcmd="$chgrpprog $2"
          141  +	shift;;
          142  +
          143  +    --help) echo "$usage"; exit $?;;
          144  +
          145  +    -m) mode=$2
          146  +	case $mode in
          147  +	  *' '* | *'	'* | *'
          148  +'*	  | *'*'* | *'?'* | *'['*)
          149  +	    echo "$0: invalid mode: $mode" >&2
          150  +	    exit 1;;
          151  +	esac
          152  +	shift;;
          153  +
          154  +    -o) chowncmd="$chownprog $2"
          155  +	shift;;
          156  +
          157  +    -s) stripcmd=$stripprog;;
          158  +
          159  +    -S) stripcmd="$stripprog $2"
          160  +	shift;;
          161  +
          162  +    -t) dst_arg=$2
          163  +	shift;;
          164  +
          165  +    -T) no_target_directory=true;;
          166  +
          167  +    --version) echo "$0 $scriptversion"; exit $?;;
          168  +
          169  +    --)	shift
          170  +	break;;
          171  +
          172  +    -*)	echo "$0: invalid option: $1" >&2
          173  +	exit 1;;
          174  +
          175  +    *)  break;;
          176  +  esac
          177  +  shift
    74    178   done
    75    179   
    76         -if [ x"$src" = x ]
    77         -then
    78         -	echo "install:  no input file specified"
    79         -	exit 1
          180  +if test $# -ne 0 && test -z "$dir_arg$dst_arg"; then
          181  +  # When -d is used, all remaining arguments are directories to create.
          182  +  # When -t is used, the destination is already specified.
          183  +  # Otherwise, the last argument is the destination.  Remove it from $@.
          184  +  for arg
          185  +  do
          186  +    if test -n "$dst_arg"; then
          187  +      # $@ is not empty: it contains at least $arg.
          188  +      set fnord "$@" "$dst_arg"
          189  +      shift # fnord
          190  +    fi
          191  +    shift # arg
          192  +    dst_arg=$arg
          193  +  done
          194  +fi
          195  +
          196  +if test $# -eq 0; then
          197  +  if test -z "$dir_arg"; then
          198  +    echo "$0: no input file specified." >&2
          199  +    exit 1
          200  +  fi
          201  +  # It's OK to call `install-sh -d' without argument.
          202  +  # This can happen when creating conditional directories.
          203  +  exit 0
          204  +fi
          205  +
          206  +if test -z "$dir_arg"; then
          207  +  do_exit='(exit $ret); exit $ret'
          208  +  trap "ret=129; $do_exit" 1
          209  +  trap "ret=130; $do_exit" 2
          210  +  trap "ret=141; $do_exit" 13
          211  +  trap "ret=143; $do_exit" 15
          212  +
          213  +  # Set umask so as not to create temps with too-generous modes.
          214  +  # However, 'strip' requires both read and write access to temps.
          215  +  case $mode in
          216  +    # Optimize common cases.
          217  +    *644) cp_umask=133;;
          218  +    *755) cp_umask=22;;
          219  +
          220  +    *[0-7])
          221  +      if test -z "$stripcmd"; then
          222  +	u_plus_rw=
          223  +      else
          224  +	u_plus_rw='% 200'
          225  +      fi
          226  +      cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;;
          227  +    *)
          228  +      if test -z "$stripcmd"; then
          229  +	u_plus_rw=
          230  +      else
          231  +	u_plus_rw=,u+rw
          232  +      fi
          233  +      cp_umask=$mode$u_plus_rw;;
          234  +  esac
    80    235   fi
    81    236   
    82         -if [ x"$dst" = x ]
    83         -then
    84         -	echo "install:  no destination specified"
          237  +for src
          238  +do
          239  +  # Protect names starting with `-'.
          240  +  case $src in
          241  +    -*) src=./$src;;
          242  +  esac
          243  +
          244  +  if test -n "$dir_arg"; then
          245  +    dst=$src
          246  +    dstdir=$dst
          247  +    test -d "$dstdir"
          248  +    dstdir_status=$?
          249  +  else
          250  +
          251  +    # Waiting for this to be detected by the "$cpprog $src $dsttmp" command
          252  +    # might cause directories to be created, which would be especially bad
          253  +    # if $src (and thus $dsttmp) contains '*'.
          254  +    if test ! -f "$src" && test ! -d "$src"; then
          255  +      echo "$0: $src does not exist." >&2
          256  +      exit 1
          257  +    fi
          258  +
          259  +    if test -z "$dst_arg"; then
          260  +      echo "$0: no destination specified." >&2
          261  +      exit 1
          262  +    fi
          263  +
          264  +    dst=$dst_arg
          265  +    # Protect names starting with `-'.
          266  +    case $dst in
          267  +      -*) dst=./$dst;;
          268  +    esac
          269  +
          270  +    # If destination is a directory, append the input filename; won't work
          271  +    # if double slashes aren't ignored.
          272  +    if test -d "$dst"; then
          273  +      if test -n "$no_target_directory"; then
          274  +	echo "$0: $dst_arg: Is a directory" >&2
    85    275   	exit 1
    86         -fi
          276  +      fi
          277  +      dstdir=$dst
          278  +      dst=$dstdir/`basename "$src"`
          279  +      dstdir_status=0
          280  +    else
          281  +      # Prefer dirname, but fall back on a substitute if dirname fails.
          282  +      dstdir=`
          283  +	(dirname "$dst") 2>/dev/null ||
          284  +	expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
          285  +	     X"$dst" : 'X\(//\)[^/]' \| \
          286  +	     X"$dst" : 'X\(//\)$' \| \
          287  +	     X"$dst" : 'X\(/\)' \| . 2>/dev/null ||
          288  +	echo X"$dst" |
          289  +	    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
          290  +		   s//\1/
          291  +		   q
          292  +		 }
          293  +		 /^X\(\/\/\)[^/].*/{
          294  +		   s//\1/
          295  +		   q
          296  +		 }
          297  +		 /^X\(\/\/\)$/{
          298  +		   s//\1/
          299  +		   q
          300  +		 }
          301  +		 /^X\(\/\).*/{
          302  +		   s//\1/
          303  +		   q
          304  +		 }
          305  +		 s/.*/./; q'
          306  +      `
          307  +
          308  +      test -d "$dstdir"
          309  +      dstdir_status=$?
          310  +    fi
          311  +  fi
          312  +
          313  +  obsolete_mkdir_used=false
          314  +
          315  +  if test $dstdir_status != 0; then
          316  +    case $posix_mkdir in
          317  +      '')
          318  +	# Create intermediate dirs using mode 755 as modified by the umask.
          319  +	# This is like FreeBSD 'install' as of 1997-10-28.
          320  +	umask=`umask`
          321  +	case $stripcmd.$umask in
          322  +	  # Optimize common cases.
          323  +	  *[2367][2367]) mkdir_umask=$umask;;
          324  +	  .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;;
          325  +
          326  +	  *[0-7])
          327  +	    mkdir_umask=`expr $umask + 22 \
          328  +	      - $umask % 100 % 40 + $umask % 20 \
          329  +	      - $umask % 10 % 4 + $umask % 2
          330  +	    `;;
          331  +	  *) mkdir_umask=$umask,go-w;;
          332  +	esac
          333  +
          334  +	# With -d, create the new directory with the user-specified mode.
          335  +	# Otherwise, rely on $mkdir_umask.
          336  +	if test -n "$dir_arg"; then
          337  +	  mkdir_mode=-m$mode
          338  +	else
          339  +	  mkdir_mode=
          340  +	fi
          341  +
          342  +	posix_mkdir=false
          343  +	case $umask in
          344  +	  *[123567][0-7][0-7])
          345  +	    # POSIX mkdir -p sets u+wx bits regardless of umask, which
          346  +	    # is incompatible with FreeBSD 'install' when (umask & 300) != 0.
          347  +	    ;;
          348  +	  *)
          349  +	    tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$
          350  +	    trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0
          351  +
          352  +	    if (umask $mkdir_umask &&
          353  +		exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1
          354  +	    then
          355  +	      if test -z "$dir_arg" || {
          356  +		   # Check for POSIX incompatibilities with -m.
          357  +		   # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or
          358  +		   # other-writeable bit of parent directory when it shouldn't.
          359  +		   # FreeBSD 6.1 mkdir -m -p sets mode of existing directory.
          360  +		   ls_ld_tmpdir=`ls -ld "$tmpdir"`
          361  +		   case $ls_ld_tmpdir in
          362  +		     d????-?r-*) different_mode=700;;
          363  +		     d????-?--*) different_mode=755;;
          364  +		     *) false;;
          365  +		   esac &&
          366  +		   $mkdirprog -m$different_mode -p -- "$tmpdir" && {
          367  +		     ls_ld_tmpdir_1=`ls -ld "$tmpdir"`
          368  +		     test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1"
          369  +		   }
          370  +		 }
          371  +	      then posix_mkdir=:
          372  +	      fi
          373  +	      rmdir "$tmpdir/d" "$tmpdir"
          374  +	    else
          375  +	      # Remove any dirs left behind by ancient mkdir implementations.
          376  +	      rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null
          377  +	    fi
          378  +	    trap '' 0;;
          379  +	esac;;
          380  +    esac
          381  +
          382  +    if
          383  +      $posix_mkdir && (
          384  +	umask $mkdir_umask &&
          385  +	$doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir"
          386  +      )
          387  +    then :
          388  +    else
          389  +
          390  +      # The umask is ridiculous, or mkdir does not conform to POSIX,
          391  +      # or it failed possibly due to a race condition.  Create the
          392  +      # directory the slow way, step by step, checking for races as we go.
          393  +
          394  +      case $dstdir in
          395  +	/*) prefix='/';;
          396  +	-*) prefix='./';;
          397  +	*)  prefix='';;
          398  +      esac
          399  +
          400  +      eval "$initialize_posix_glob"
          401  +
          402  +      oIFS=$IFS
          403  +      IFS=/
          404  +      $posix_glob set -f
          405  +      set fnord $dstdir
          406  +      shift
          407  +      $posix_glob set +f
          408  +      IFS=$oIFS
          409  +
          410  +      prefixes=
          411  +
          412  +      for d
          413  +      do
          414  +	test -z "$d" && continue
          415  +
          416  +	prefix=$prefix$d
          417  +	if test -d "$prefix"; then
          418  +	  prefixes=
          419  +	else
          420  +	  if $posix_mkdir; then
          421  +	    (umask=$mkdir_umask &&
          422  +	     $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break
          423  +	    # Don't fail if two instances are running concurrently.
          424  +	    test -d "$prefix" || exit 1
          425  +	  else
          426  +	    case $prefix in
          427  +	      *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;;
          428  +	      *) qprefix=$prefix;;
          429  +	    esac
          430  +	    prefixes="$prefixes '$qprefix'"
          431  +	  fi
          432  +	fi
          433  +	prefix=$prefix/
          434  +      done
          435  +
          436  +      if test -n "$prefixes"; then
          437  +	# Don't fail if two instances are running concurrently.
          438  +	(umask $mkdir_umask &&
          439  +	 eval "\$doit_exec \$mkdirprog $prefixes") ||
          440  +	  test -d "$dstdir" || exit 1
          441  +	obsolete_mkdir_used=true
          442  +      fi
          443  +    fi
          444  +  fi
          445  +
          446  +  if test -n "$dir_arg"; then
          447  +    { test -z "$chowncmd" || $doit $chowncmd "$dst"; } &&
          448  +    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } &&
          449  +    { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false ||
          450  +      test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1
          451  +  else
          452  +
          453  +    # Make a couple of temp file names in the proper directory.
          454  +    dsttmp=$dstdir/_inst.$$_
          455  +    rmtmp=$dstdir/_rm.$$_
          456  +
          457  +    # Trap to clean up those temp files at exit.
          458  +    trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0
          459  +
          460  +    # Copy the file name to the temp name.
          461  +    (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") &&
          462  +
          463  +    # and set any options; do chmod last to preserve setuid bits.
          464  +    #
          465  +    # If any of these fail, we abort the whole thing.  If we want to
          466  +    # ignore errors from any of these, just make sure not to ignore
          467  +    # errors from the above "$doit $cpprog $src $dsttmp" command.
          468  +    #
          469  +    { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } &&
          470  +    { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } &&
          471  +    { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } &&
          472  +    { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } &&
          473  +
          474  +    # If -C, don't bother to copy if it wouldn't change the file.
          475  +    if $copy_on_change &&
          476  +       old=`LC_ALL=C ls -dlL "$dst"	2>/dev/null` &&
          477  +       new=`LC_ALL=C ls -dlL "$dsttmp"	2>/dev/null` &&
          478  +
          479  +       eval "$initialize_posix_glob" &&
          480  +       $posix_glob set -f &&
          481  +       set X $old && old=:$2:$4:$5:$6 &&
          482  +       set X $new && new=:$2:$4:$5:$6 &&
          483  +       $posix_glob set +f &&
    87    484   
          485  +       test "$old" = "$new" &&
          486  +       $cmpprog "$dst" "$dsttmp" >/dev/null 2>&1
          487  +    then
          488  +      rm -f "$dsttmp"
          489  +    else
          490  +      # Rename the file to the real destination.
          491  +      $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null ||
    88    492   
    89         -# If destination is a directory, append the input filename; if your system
    90         -# does not like double slashes in filenames, you may need to add some logic
          493  +      # The rename failed, perhaps because mv can't rename something else
          494  +      # to itself, or perhaps because mv is so ancient that it does not
          495  +      # support -f.
          496  +      {
          497  +	# Now remove or move aside any old file at destination location.
          498  +	# We try this two ways since rm can't unlink itself on some
          499  +	# systems and the destination file might be busy for other
          500  +	# reasons.  In this case, the final cleanup might fail but the new
          501  +	# file should still install successfully.
          502  +	{
          503  +	  test ! -f "$dst" ||
          504  +	  $doit $rmcmd -f "$dst" 2>/dev/null ||
          505  +	  { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null &&
          506  +	    { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }
          507  +	  } ||
          508  +	  { echo "$0: cannot unlink or rename $dst" >&2
          509  +	    (exit 1); exit 1
          510  +	  }
          511  +	} &&
    91    512   
    92         -if [ -d $dst ]
    93         -then
    94         -	dst="$dst"/`basename $src`
    95         -fi
          513  +	# Now rename the file to the real destination.
          514  +	$doit $mvcmd "$dsttmp" "$dst"
          515  +      }
          516  +    fi || exit 1
    96    517   
    97         -# Make a temp file name in the proper directory.
    98         -
    99         -dstdir=`dirname $dst`
   100         -dsttmp=$dstdir/#inst.$$#
   101         -
   102         -# Move or copy the file name to the temp name
          518  +    trap '' 0
          519  +  fi
          520  +done
   103    521   
   104         -$doit $instcmd $src $dsttmp
   105         -
   106         -# and set any options; do chmod last to preserve setuid bits
   107         -
   108         -if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; fi
   109         -if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; fi
   110         -if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; fi
   111         -if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; fi
   112         -
   113         -# Now rename the file to the real destination.
   114         -
   115         -$doit $rmcmd $dst
   116         -$doit $mvcmd $dsttmp $dst
   117         -
   118         -
   119         -exit 0
          522  +# Local variables:
          523  +# eval: (add-hook 'write-file-hooks 'time-stamp)
          524  +# time-stamp-start: "scriptversion="
          525  +# time-stamp-format: "%:y-%02m-%02d.%02H"
          526  +# time-stamp-time-zone: "UTC"
          527  +# time-stamp-end: "; # UTC"
          528  +# End:

Changes to autoconf/tea/tclconfig/tcl.m4.

     4      4   #	a Tcl extension.
     5      5   #
     6      6   # Copyright (c) 1999-2000 Ajuba Solutions.
     7      7   # Copyright (c) 2002-2005 ActiveState Corporation.
     8      8   #
     9      9   # See the file "license.terms" for information on usage and redistribution
    10     10   # of this file, and for a DISCLAIMER OF ALL WARRANTIES.
    11         -#
    12         -# RCS: @(#) $Id: tcl.m4,v 1.145 2010/08/17 00:33:40 hobbs Exp $
    13     11   
    14     12   AC_PREREQ(2.57)
    15     13   
    16     14   dnl TEA extensions pass us the version of TEA they think they
    17     15   dnl are compatible with (must be set in TEA_INIT below)
    18     16   dnl TEA_VERSION="3.9"
    19     17   
................................................................................
   136    134   		for i in `ls -d ${libdir} 2>/dev/null` \
   137    135   			`ls -d ${exec_prefix}/lib 2>/dev/null` \
   138    136   			`ls -d ${prefix}/lib 2>/dev/null` \
   139    137   			`ls -d /usr/local/lib 2>/dev/null` \
   140    138   			`ls -d /usr/contrib/lib 2>/dev/null` \
   141    139   			`ls -d /usr/lib 2>/dev/null` \
   142    140   			`ls -d /usr/lib64 2>/dev/null` \
          141  +			`ls -d /usr/lib/tcl8.6 2>/dev/null` \
          142  +			`ls -d /usr/lib/tcl8.5 2>/dev/null` \
   143    143   			; do
   144    144   		    if test -f "$i/tclConfig.sh" ; then
   145    145   			ac_cv_c_tclconfig="`(cd $i; pwd)`"
   146    146   			break
   147    147   		    fi
   148    148   		done
   149    149   	    fi
................................................................................
   166    166   		    fi
   167    167   		done
   168    168   	    fi
   169    169   	])
   170    170   
   171    171   	if test x"${ac_cv_c_tclconfig}" = x ; then
   172    172   	    TCL_BIN_DIR="# no Tcl configs found"
   173         -	    AC_MSG_ERROR([Can't find Tcl configuration definitions])
          173  +	    AC_MSG_ERROR([Can't find Tcl configuration definitions. Use --with-tcl to specify a directory containing tclConfig.sh])
   174    174   	else
   175    175   	    no_tcl=
   176    176   	    TCL_BIN_DIR="${ac_cv_c_tclconfig}"
   177    177   	    AC_MSG_RESULT([found ${TCL_BIN_DIR}/tclConfig.sh])
   178    178   	fi
   179    179       fi
   180    180   ])
................................................................................
   319    319   		    fi
   320    320   		done
   321    321   	    fi
   322    322   	])
   323    323   
   324    324   	if test x"${ac_cv_c_tkconfig}" = x ; then
   325    325   	    TK_BIN_DIR="# no Tk configs found"
   326         -	    AC_MSG_ERROR([Can't find Tk configuration definitions])
          326  +	    AC_MSG_ERROR([Can't find Tk configuration definitions. Use --with-tk to specify a directory containing tkConfig.sh])
   327    327   	else
   328    328   	    no_tk=
   329    329   	    TK_BIN_DIR="${ac_cv_c_tkconfig}"
   330    330   	    AC_MSG_RESULT([found ${TK_BIN_DIR}/tkConfig.sh])
   331    331   	fi
   332    332       fi
   333    333   ])
................................................................................
   340    340   # Arguments:
   341    341   #
   342    342   #	Requires the following vars to be set:
   343    343   #		TCL_BIN_DIR
   344    344   #
   345    345   # Results:
   346    346   #
   347         -#	Subst the following vars:
          347  +#	Substitutes the following vars:
   348    348   #		TCL_BIN_DIR
   349    349   #		TCL_SRC_DIR
   350    350   #		TCL_LIB_FILE
   351         -#
   352    351   #------------------------------------------------------------------------
   353    352   
   354    353   AC_DEFUN([TEA_LOAD_TCLCONFIG], [
   355    354       AC_MSG_CHECKING([for existence of ${TCL_BIN_DIR}/tclConfig.sh])
   356    355   
   357    356       if test -f "${TCL_BIN_DIR}/tclConfig.sh" ; then
   358    357           AC_MSG_RESULT([loading])
................................................................................
   413    412       AC_SUBST(TCL_LIB_FLAG)
   414    413       AC_SUBST(TCL_LIB_SPEC)
   415    414   
   416    415       AC_SUBST(TCL_STUB_LIB_FILE)
   417    416       AC_SUBST(TCL_STUB_LIB_FLAG)
   418    417       AC_SUBST(TCL_STUB_LIB_SPEC)
   419    418   
   420         -    case "`uname -s`" in
   421         -	*CYGWIN_*)
   422         -	    AC_MSG_CHECKING([for cygwin variant])
   423         -	    case ${TCL_EXTRA_CFLAGS} in
   424         -		*-mwin32*|*-mno-cygwin*)
   425         -		    TEA_PLATFORM="windows"
   426         -		    CFLAGS="$CFLAGS -mwin32"
   427         -		    AC_MSG_RESULT([win32])
   428         -		    ;;
   429         -		*)
   430         -		    TEA_PLATFORM="unix"
   431         -		    AC_MSG_RESULT([unix])
   432         -		    ;;
   433         -	    esac
   434         -	    EXEEXT=".exe"
   435         -	    ;;
   436         -	*)
   437         -	    ;;
   438         -    esac
          419  +    AC_MSG_CHECKING([platform])
          420  +    hold_cc=$CC; CC="$TCL_CC"
          421  +    AC_TRY_COMPILE(,[
          422  +	    #ifdef _WIN32
          423  +		#error win32
          424  +	    #endif
          425  +    ], TEA_PLATFORM="unix",
          426  +	    TEA_PLATFORM="windows"
          427  +    )
          428  +    CC=$hold_cc
          429  +    AC_MSG_RESULT($TEA_PLATFORM)
   439    430   
          431  +    # The BUILD_$pkg is to define the correct extern storage class
          432  +    # handling when making this package
          433  +    AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME}, [],
          434  +	    [Building extension source?])
   440    435       # Do this here as we have fully defined TEA_PLATFORM now
   441    436       if test "${TEA_PLATFORM}" = "windows" ; then
   442         -	# The BUILD_$pkg is to define the correct extern storage class
   443         -	# handling when making this package
   444         -	AC_DEFINE_UNQUOTED(BUILD_${PACKAGE_NAME})
   445         -	CLEANFILES="$CLEANFILES *.lib *.dll *.pdb"
          437  +	EXEEXT=".exe"
          438  +	CLEANFILES="$CLEANFILES *.lib *.dll *.pdb *.exp"
   446    439       fi
   447    440   
   448    441       # TEA specific:
   449    442       AC_SUBST(CLEANFILES)
   450    443       AC_SUBST(TCL_LIBS)
   451    444       AC_SUBST(TCL_DEFS)
   452    445       AC_SUBST(TCL_EXTRA_CFLAGS)
................................................................................
   562    555   #	directory. This macro will correctly determine the name
   563    556   #	of the tclsh executable even if tclsh has not yet been
   564    557   #	built in the build directory. The tclsh found is always
   565    558   #	associated with a tclConfig.sh file. This tclsh should be used
   566    559   #	only for running extension test cases. It should never be
   567    560   #	or generation of files (like pkgIndex.tcl) at build time.
   568    561   #
   569         -# Arguments
          562  +# Arguments:
   570    563   #	none
   571    564   #
   572         -# Results
   573         -#	Subst's the following values:
          565  +# Results:
          566  +#	Substitutes the following vars:
   574    567   #		TCLSH_PROG
   575    568   #------------------------------------------------------------------------
   576    569   
   577    570   AC_DEFUN([TEA_PROG_TCLSH], [
   578    571       AC_MSG_CHECKING([for tclsh])
   579    572       if test -f "${TCL_BIN_DIR}/Makefile" ; then
   580    573           # tclConfig.sh is in Tcl build directory
................................................................................
   612    605   #	directory. This macro will correctly determine the name
   613    606   #	of the wish executable even if wish has not yet been
   614    607   #	built in the build directory. The wish found is always
   615    608   #	associated with a tkConfig.sh file. This wish should be used
   616    609   #	only for running extension test cases. It should never be
   617    610   #	or generation of files (like pkgIndex.tcl) at build time.
   618    611   #
   619         -# Arguments
          612  +# Arguments:
   620    613   #	none
   621    614   #
   622         -# Results
   623         -#	Subst's the following values:
          615  +# Results:
          616  +#	Substitutes the following vars:
   624    617   #		WISH_PROG
   625    618   #------------------------------------------------------------------------
   626    619   
   627    620   AC_DEFUN([TEA_PROG_WISH], [
   628    621       AC_MSG_CHECKING([for wish])
   629    622       if test -f "${TK_BIN_DIR}/Makefile" ; then
   630    623           # tkConfig.sh is in Tk build directory
................................................................................
   727    720   #	Sets the following vars:
   728    721   #		THREADS_LIBS	Thread library(s)
   729    722   #
   730    723   #	Defines the following vars:
   731    724   #		TCL_THREADS
   732    725   #		_REENTRANT
   733    726   #		_THREAD_SAFE
   734         -#
   735    727   #------------------------------------------------------------------------
   736    728   
   737    729   AC_DEFUN([TEA_ENABLE_THREADS], [
   738    730       AC_ARG_ENABLE(threads,
   739    731   	AC_HELP_STRING([--enable-threads],
   740    732   	    [build with threads]),
   741    733   	[tcl_ok=$enableval], [tcl_ok=yes])
................................................................................
   851    843   # Results:
   852    844   #
   853    845   #	Adds the following arguments to configure:
   854    846   #		--enable-symbols
   855    847   #
   856    848   #	Defines the following vars:
   857    849   #		CFLAGS_DEFAULT	Sets to $(CFLAGS_DEBUG) if true
   858         -#				Sets to $(CFLAGS_OPTIMIZE) if false
          850  +#				Sets to "$(CFLAGS_OPTIMIZE) -DNDEBUG" if false
   859    851   #		LDFLAGS_DEFAULT	Sets to $(LDFLAGS_DEBUG) if true
   860    852   #				Sets to $(LDFLAGS_OPTIMIZE) if false
   861    853   #		DBGX		Formerly used as debug library extension;
   862    854   #				always blank now.
   863         -#
   864    855   #------------------------------------------------------------------------
   865    856   
   866    857   AC_DEFUN([TEA_ENABLE_SYMBOLS], [
   867    858       dnl TEA specific: Make sure we are initialized
   868    859       AC_REQUIRE([TEA_CONFIG_CFLAGS])
   869    860       AC_MSG_CHECKING([for build with symbols])
   870    861       AC_ARG_ENABLE(symbols,
   871    862   	AC_HELP_STRING([--enable-symbols],
   872    863   	    [build with debugging symbols (default: off)]),
   873    864   	[tcl_ok=$enableval], [tcl_ok=no])
   874    865       DBGX=""
   875    866       if test "$tcl_ok" = "no"; then
   876         -	CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE}"
          867  +	CFLAGS_DEFAULT="${CFLAGS_OPTIMIZE} -DNDEBUG"
   877    868   	LDFLAGS_DEFAULT="${LDFLAGS_OPTIMIZE}"
   878    869   	AC_MSG_RESULT([no])
   879    870       else
   880    871   	CFLAGS_DEFAULT="${CFLAGS_DEBUG}"
   881    872   	LDFLAGS_DEFAULT="${LDFLAGS_DEBUG}"
   882    873   	if test "$tcl_ok" = "yes"; then
   883    874   	    AC_MSG_RESULT([yes (standard debugging)])
................................................................................
   916    907   # Results:
   917    908   #
   918    909   #	Adds the following arguments to configure:
   919    910   #		--enable-langinfo=yes|no (default is yes)
   920    911   #
   921    912   #	Defines the following vars:
   922    913   #		HAVE_LANGINFO	Triggers use of nl_langinfo if defined.
   923         -#
   924    914   #------------------------------------------------------------------------
   925    915   
   926    916   AC_DEFUN([TEA_ENABLE_LANGINFO], [
   927    917       AC_ARG_ENABLE(langinfo,
   928    918   	AC_HELP_STRING([--enable-langinfo],
   929    919   	    [use nl_langinfo if possible to determine encoding at startup, otherwise use old heuristic (default: on)]),
   930    920   	[langinfo_ok=$enableval], [langinfo_ok=yes])
................................................................................
   957    947   # Arguments:
   958    948   #	none
   959    949   #
   960    950   # Results:
   961    951   #	Defines the following var:
   962    952   #
   963    953   #	system -	System/platform/version identification code.
   964         -#
   965    954   #--------------------------------------------------------------------
   966    955   
   967    956   AC_DEFUN([TEA_CONFIG_SYSTEM], [
   968    957       AC_CACHE_CHECK([system version], tcl_cv_sys_version, [
   969    958   	# TEA specific:
   970    959   	if test "${TEA_PLATFORM}" = "windows" ; then
   971    960   	    tcl_cv_sys_version=windows
................................................................................
  1026   1015   #                       general if Tcl and Tk aren't themselves shared
  1027   1016   #                       libraries), then this symbol has an empty string
  1028   1017   #                       as its value.
  1029   1018   #       SHLIB_SUFFIX -  Suffix to use for the names of dynamically loadable
  1030   1019   #                       extensions.  An empty string means we don't know how
  1031   1020   #                       to use shared libraries on this platform.
  1032   1021   #       LIB_SUFFIX -    Specifies everything that comes after the "libfoo"
  1033         -#                       in a static or shared library name, using the $VERSION variable
         1022  +#                       in a static or shared library name, using the $PACKAGE_VERSION variable
  1034   1023   #                       to put the version in the right place.  This is used
  1035   1024   #                       by platforms that need non-standard library names.
  1036         -#                       Examples:  ${VERSION}.so.1.1 on NetBSD, since it needs
  1037         -#                       to have a version after the .so, and ${VERSION}.a
         1025  +#                       Examples:  ${PACKAGE_VERSION}.so.1.1 on NetBSD, since it needs
         1026  +#                       to have a version after the .so, and ${PACKAGE_VERSION}.a
  1038   1027   #                       on AIX, since a shared library needs to have
  1039   1028   #                       a .a extension whereas shared objects for loadable
  1040   1029   #                       extensions have a .so extension.  Defaults to
  1041         -#                       ${VERSION}${SHLIB_SUFFIX}.
         1030  +#                       ${PACKAGE_VERSION}${SHLIB_SUFFIX}.
  1042   1031   #	CFLAGS_DEBUG -
  1043   1032   #			Flags used when running the compiler in debug mode
  1044   1033   #	CFLAGS_OPTIMIZE -
  1045   1034   #			Flags used when running the compiler in optimize mode
  1046   1035   #	CFLAGS -	Additional CFLAGS added as necessary (usually 64-bit)
  1047         -#
  1048   1036   #--------------------------------------------------------------------
  1049   1037   
  1050   1038   AC_DEFUN([TEA_CONFIG_CFLAGS], [
  1051   1039       dnl TEA specific: Make sure we are initialized
  1052   1040       AC_REQUIRE([TEA_INIT])
  1053   1041   
  1054   1042       # Step 0.a: Enable 64 bit support?
................................................................................
  1082   1070   	    void f(void) {}], [f();], tcl_cv_cc_visibility_hidden=yes,
  1083   1071   	    tcl_cv_cc_visibility_hidden=no)
  1084   1072   	CFLAGS=$hold_cflags])
  1085   1073       AS_IF([test $tcl_cv_cc_visibility_hidden = yes], [
  1086   1074   	AC_DEFINE(MODULE_SCOPE,
  1087   1075   	    [extern __attribute__((__visibility__("hidden")))],
  1088   1076   	    [Compiler support for module scope symbols])
         1077  +	AC_DEFINE(HAVE_HIDDEN, [1], [Compiler support for module scope symbols])
  1089   1078       ])
  1090   1079   
  1091   1080       # Step 0.d: Disable -rpath support?
  1092   1081   
  1093   1082       AC_MSG_CHECKING([if rpath support is requested])
  1094   1083       AC_ARG_ENABLE(rpath,
  1095   1084   	AC_HELP_STRING([--disable-rpath],
................................................................................
  1130   1119       LDFLAGS_ARCH=""
  1131   1120       UNSHARED_LIB_SUFFIX=""
  1132   1121       # TEA specific: use PACKAGE_VERSION instead of VERSION
  1133   1122       TCL_TRIM_DOTS='`echo ${PACKAGE_VERSION} | tr -d .`'
  1134   1123       ECHO_VERSION='`echo ${PACKAGE_VERSION}`'
  1135   1124       TCL_LIB_VERSIONS_OK=ok
  1136   1125       CFLAGS_DEBUG=-g
  1137         -    CFLAGS_OPTIMIZE=-O
  1138   1126       AS_IF([test "$GCC" = yes], [
  1139         -	# TEA specific:
  1140   1127   	CFLAGS_OPTIMIZE=-O2
  1141   1128   	CFLAGS_WARNING="-Wall"
  1142         -    ], [CFLAGS_WARNING=""])
  1143         -dnl FIXME: Replace AC_CHECK_PROG with AC_CHECK_TOOL once cross compiling is fixed.
  1144         -dnl AC_CHECK_TOOL(AR, ar)
  1145         -    AC_CHECK_PROG(AR, ar, ar)
         1129  +    ], [
         1130  +	CFLAGS_OPTIMIZE=-O
         1131  +	CFLAGS_WARNING=""
         1132  +    ])
         1133  +    AC_CHECK_TOOL(AR, ar)
  1146   1134       STLIB_LD='${AR} cr'
  1147   1135       LD_LIBRARY_PATH_VAR="LD_LIBRARY_PATH"
  1148   1136       AS_IF([test "x$SHLIB_VERSION" = x],[SHLIB_VERSION="1.0"])
  1149   1137       case $system in
  1150   1138   	# TEA specific:
  1151   1139   	windows)
  1152   1140   	    # This is a 2-stage check to make sure we have the 64-bit SDK
................................................................................
  1167   1155   			PATH64="${MSSDK}/Bin/Win64/x86/AMD64"
  1168   1156   			;;
  1169   1157   		    ia64)
  1170   1158   			MACHINE="IA64"
  1171   1159   			PATH64="${MSSDK}/Bin/Win64"
  1172   1160   			;;
  1173   1161   		esac
  1174         -		if test ! -d "${PATH64}" ; then
         1162  +		if test "$GCC" != "yes" -a ! -d "${PATH64}" ; then
  1175   1163   		    AC_MSG_WARN([Could not find 64-bit $MACHINE SDK to enable 64bit mode])
  1176   1164   		    AC_MSG_WARN([Ensure latest Platform SDK is installed])
  1177   1165   		    do64bit="no"
  1178   1166   		else
  1179   1167   		    AC_MSG_RESULT([   Using 64-bit $MACHINE mode])
  1180   1168   		    do64bit_ok="yes"
  1181   1169   		fi
................................................................................
  1284   1272   		    lversion=`echo ${CEVERSION} | sed -e 's/\(.\)\(..\)/\1\.\2/'`
  1285   1273   		    lflags="-MACHINE:${ARCH} -LIBPATH:\"${CELIBPATH}\" -subsystem:windowsce,${lversion} -nologo"
  1286   1274   		    LINKBIN="\"${CEBINROOT}/link.exe\""
  1287   1275   		    AC_SUBST(CELIB_DIR)
  1288   1276   		else
  1289   1277   		    RC="rc"
  1290   1278   		    lflags="-nologo"
  1291         -    		    LINKBIN="link"
         1279  +		    LINKBIN="link"
  1292   1280   		    CFLAGS_DEBUG="-nologo -Z7 -Od -W3 -WX ${runtime}d"
  1293   1281   		    CFLAGS_OPTIMIZE="-nologo -O2 -W2 ${runtime}"
  1294   1282   		fi
  1295   1283   	    fi
  1296   1284   
  1297   1285   	    if test "$GCC" = "yes"; then
  1298   1286   		# mingw gcc mode
  1299         -		RC="windres"
         1287  +		AC_CHECK_TOOL(RC, windres)
  1300   1288   		CFLAGS_DEBUG="-g"
  1301   1289   		CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
  1302         -		SHLIB_LD="$CC -shared"
         1290  +		SHLIB_LD='${CC} -shared'
  1303   1291   		UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
  1304   1292   		LDFLAGS_CONSOLE="-wl,--subsystem,console ${lflags}"
  1305   1293   		LDFLAGS_WINDOW="-wl,--subsystem,windows ${lflags}"
         1294  +
         1295  +		AC_CACHE_CHECK(for cross-compile version of gcc,
         1296  +			ac_cv_cross,
         1297  +			AC_TRY_COMPILE([
         1298  +			    #ifdef _WIN32
         1299  +				#error cross-compiler
         1300  +			    #endif
         1301  +			], [],
         1302  +			ac_cv_cross=yes,
         1303  +			ac_cv_cross=no)
         1304  +		      )
         1305  +		      if test "$ac_cv_cross" = "yes"; then
         1306  +			case "$do64bit" in
         1307  +			    amd64|x64|yes)
         1308  +				CC="x86_64-w64-mingw32-gcc"
         1309  +				LD="x86_64-w64-mingw32-ld"
         1310  +				AR="x86_64-w64-mingw32-ar"
         1311  +				RANLIB="x86_64-w64-mingw32-ranlib"
         1312  +				RC="x86_64-w64-mingw32-windres"
         1313  +			    ;;
         1314  +			    *)
         1315  +				CC="i686-w64-mingw32-gcc"
         1316  +				LD="i686-w64-mingw32-ld"
         1317  +				AR="i686-w64-mingw32-ar"
         1318  +				RANLIB="i686-w64-mingw32-ranlib"
         1319  +				RC="i686-w64-mingw32-windres"
         1320  +			    ;;
         1321  +			esac
         1322  +		fi
         1323  +
  1306   1324   	    else
  1307   1325   		SHLIB_LD="${LINKBIN} -dll ${lflags}"
  1308   1326   		# link -lib only works when -lib is the first arg
  1309   1327   		STLIB_LD="${LINKBIN} -lib ${lflags}"
  1310   1328   		UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.lib'
  1311   1329   		PATHTYPE=-w
  1312   1330   		# For information on what debugtype is most useful, see:
................................................................................
  1405   1423   	    CC_SEARCH_FLAGS=""
  1406   1424   	    LD_SEARCH_FLAGS=""
  1407   1425   	    ;;
  1408   1426   	CYGWIN_*)
  1409   1427   	    SHLIB_CFLAGS=""
  1410   1428   	    SHLIB_LD='${CC} -shared'
  1411   1429   	    SHLIB_SUFFIX=".dll"
  1412         -	    EXE_SUFFIX=".exe"
         1430  +	    EXEEXT=".exe"
         1431  +	    do64bit_ok=yes
  1413   1432   	    CC_SEARCH_FLAGS=""
  1414   1433   	    LD_SEARCH_FLAGS=""
  1415   1434   	    ;;
  1416   1435   	Haiku*)
  1417   1436   	    LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
  1418   1437   	    SHLIB_CFLAGS="-fPIC"
  1419   1438   	    SHLIB_SUFFIX=".so"
................................................................................
  1434   1453   		#   CPPFLAGS="-AA"
  1435   1454   		#fi
  1436   1455   	    ], [
  1437   1456   		SHLIB_SUFFIX=".sl"
  1438   1457   	    ])
  1439   1458   	    AC_CHECK_LIB(dld, shl_load, tcl_ok=yes, tcl_ok=no)
  1440   1459   	    AS_IF([test "$tcl_ok" = yes], [
  1441         -		LDFLAGS="$LDFLAGS -E"
         1460  +		LDFLAGS="$LDFLAGS -Wl,-E"
  1442   1461   		CC_SEARCH_FLAGS='-Wl,+s,+b,${LIB_RUNTIME_DIR}:.'
  1443   1462   		LD_SEARCH_FLAGS='+s +b ${LIB_RUNTIME_DIR}:.'
  1444   1463   		LD_LIBRARY_PATH_VAR="SHLIB_PATH"
  1445   1464   	    ])
  1446   1465   	    AS_IF([test "$GCC" = yes], [
  1447   1466   		SHLIB_LD='${CC} -shared'
  1448   1467   		LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
................................................................................
  1516   1535   	            do64bit_ok=yes
  1517   1536   	            SHLIB_LD="ld -64 -shared -rdata_shared"
  1518   1537   	            CFLAGS="$CFLAGS -64"
  1519   1538   	            LDFLAGS_ARCH="-64"
  1520   1539   	        ])
  1521   1540   	    ])
  1522   1541   	    ;;
  1523         -	Linux*)
         1542  +	Linux*|GNU*|NetBSD-Debian)
  1524   1543   	    SHLIB_CFLAGS="-fPIC"
  1525   1544   	    SHLIB_SUFFIX=".so"
  1526   1545   
  1527   1546   	    # TEA specific:
  1528   1547   	    CFLAGS_OPTIMIZE="-O2 -fomit-frame-pointer"
  1529   1548   
  1530   1549   	    # TEA specific: use LDFLAGS_DEFAULT instead of LDFLAGS
................................................................................
  1549   1568   	    # The combo of gcc + glibc has a bug related to inlining of
  1550   1569   	    # functions like strtod(). The -fno-builtin flag should address
  1551   1570   	    # this problem but it does not work. The -fno-inline flag is kind
  1552   1571   	    # of overkill but it works. Disable inlining only when one of the
  1553   1572   	    # files in compat/*.c is being linked in.
  1554   1573   
  1555   1574   	    AS_IF([test x"${USE_COMPAT}" != x],[CFLAGS="$CFLAGS -fno-inline"])
  1556         -
  1557         -	    ;;
  1558         -	GNU*)
  1559         -	    SHLIB_CFLAGS="-fPIC"
  1560         -	    SHLIB_SUFFIX=".so"
  1561         -
  1562         -	    SHLIB_LD='${CC} -shared'
  1563         -	    LDFLAGS="$LDFLAGS -Wl,--export-dynamic"
  1564         -	    CC_SEARCH_FLAGS=""
  1565         -	    LD_SEARCH_FLAGS=""
  1566         -	    AS_IF([test "`uname -m`" = "alpha"], [CFLAGS="$CFLAGS -mieee"])
  1567   1575   	    ;;
  1568   1576   	Lynx*)
  1569   1577   	    SHLIB_CFLAGS="-fPIC"
  1570   1578   	    SHLIB_SUFFIX=".so"
  1571   1579   	    CFLAGS_OPTIMIZE=-02
  1572   1580   	    SHLIB_LD='${CC} -shared'
  1573   1581   	    LD_FLAGS="-Wl,--export-dynamic"
  1574   1582   	    AS_IF([test $doRpath = yes], [
  1575   1583   		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
  1576   1584   		LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
  1577   1585   	    ;;
  1578   1586   	OpenBSD-*)
  1579         -	    SHLIB_CFLAGS="-fPIC"
  1580         -	    SHLIB_LD='${CC} -shared ${SHLIB_CFLAGS}'
  1581         -	    SHLIB_SUFFIX=".so"
  1582         -	    AS_IF([test $doRpath = yes], [
  1583         -		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
  1584         -	    LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
  1585         -	    SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so.${SHLIB_VERSION}'
  1586         -	    AC_CACHE_CHECK([for ELF], tcl_cv_ld_elf, [
  1587         -		AC_EGREP_CPP(yes, [
  1588         -#ifdef __ELF__
  1589         -	yes
  1590         -#endif
  1591         -		], tcl_cv_ld_elf=yes, tcl_cv_ld_elf=no)])
  1592         -	    AS_IF([test $tcl_cv_ld_elf = yes], [
  1593         -		LDFLAGS=-Wl,-export-dynamic
  1594         -	    ], [LDFLAGS=""])
         1587  +	    arch=`arch -s`
         1588  +	    case "$arch" in
         1589  +	    vax)
         1590  +		SHLIB_SUFFIX=""
         1591  +		SHARED_LIB_SUFFIX=""
         1592  +		LDFLAGS=""
         1593  +		;;
         1594  +	    *)
         1595  +		SHLIB_CFLAGS="-fPIC"
         1596  +		SHLIB_LD='${CC} -shared ${SHLIB_CFLAGS}'
         1597  +		SHLIB_SUFFIX=".so"
         1598  +		AS_IF([test $doRpath = yes], [
         1599  +		    CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
         1600  +		LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
         1601  +		SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so.${SHLIB_VERSION}'
         1602  +		LDFLAGS="-Wl,-export-dynamic"
         1603  +		;;
         1604  +	    esac
         1605  +	    case "$arch" in
         1606  +	    vax)
         1607  +		CFLAGS_OPTIMIZE="-O1"
         1608  +		;;
         1609  +	    *)
         1610  +		CFLAGS_OPTIMIZE="-O2"
         1611  +		;;
         1612  +	    esac
  1595   1613   	    AS_IF([test "${TCL_THREADS}" = "1"], [
  1596         -		# OpenBSD builds and links with -pthread, never -lpthread.
         1614  +		# On OpenBSD:	Compile with -pthread
         1615  +		#		Don't link with -lpthread
  1597   1616   		LIBS=`echo $LIBS | sed s/-lpthread//`
  1598   1617   		CFLAGS="$CFLAGS -pthread"
  1599         -		SHLIB_CFLAGS="$SHLIB_CFLAGS -pthread"
  1600   1618   	    ])
  1601   1619   	    # OpenBSD doesn't do version numbers with dots.
  1602   1620   	    UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
  1603   1621   	    TCL_LIB_VERSIONS_OK=nodots
  1604   1622   	    ;;
  1605         -	NetBSD-*|FreeBSD-[[3-4]].*)
  1606         -	    # FreeBSD 3.* and greater have ELF.
  1607         -	    # NetBSD 2.* has ELF and can use 'cc -shared' to build shared libs
         1623  +	NetBSD-*)
         1624  +	    # NetBSD has ELF and can use 'cc -shared' to build shared libs
  1608   1625   	    SHLIB_CFLAGS="-fPIC"
  1609   1626   	    SHLIB_LD='${CC} -shared ${SHLIB_CFLAGS}'
  1610   1627   	    SHLIB_SUFFIX=".so"
  1611   1628   	    LDFLAGS="$LDFLAGS -export-dynamic"
  1612   1629   	    AS_IF([test $doRpath = yes], [
  1613   1630   		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
  1614   1631   	    LD_SEARCH_FLAGS=${CC_SEARCH_FLAGS}
  1615   1632   	    AS_IF([test "${TCL_THREADS}" = "1"], [
  1616   1633   		# The -pthread needs to go in the CFLAGS, not LIBS
  1617   1634   		LIBS=`echo $LIBS | sed s/-pthread//`
  1618   1635   		CFLAGS="$CFLAGS -pthread"
  1619   1636   	    	LDFLAGS="$LDFLAGS -pthread"
  1620   1637   	    ])
  1621         -	    case $system in
  1622         -	    FreeBSD-3.*)
  1623         -	    	# FreeBSD-3 doesn't handle version numbers with dots.
  1624         -	    	UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
  1625         -	    	SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.so'
  1626         -	    	TCL_LIB_VERSIONS_OK=nodots
  1627         -		;;
  1628         -	    esac
  1629   1638   	    ;;
  1630   1639   	FreeBSD-*)
  1631   1640   	    # This configuration from FreeBSD Ports.
  1632   1641   	    SHLIB_CFLAGS="-fPIC"
  1633   1642   	    SHLIB_LD="${CC} -shared"
  1634         -	    TCL_SHLIB_LD_EXTRAS="-soname \$[@]"
         1643  +	    TCL_SHLIB_LD_EXTRAS="-Wl,-soname=\$[@]"
  1635   1644   	    SHLIB_SUFFIX=".so"
  1636   1645   	    LDFLAGS=""
  1637   1646   	    AS_IF([test $doRpath = yes], [
  1638   1647   		CC_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'
  1639         -		LD_SEARCH_FLAGS='-rpath ${LIB_RUNTIME_DIR}'])
         1648  +		LD_SEARCH_FLAGS='-Wl,-rpath,${LIB_RUNTIME_DIR}'])
  1640   1649   	    AS_IF([test "${TCL_THREADS}" = "1"], [
  1641   1650   		# The -pthread needs to go in the LDFLAGS, not LIBS
  1642   1651   		LIBS=`echo $LIBS | sed s/-pthread//`
  1643   1652   		CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
  1644   1653   		LDFLAGS="$LDFLAGS $PTHREAD_LIBS"])
  1645   1654   	    # Version numbers are dot-stripped by system policy.
  1646         -	    TCL_TRIM_DOTS=`echo ${VERSION} | tr -d .`
         1655  +	    TCL_TRIM_DOTS=`echo ${PACKAGE_VERSION} | tr -d .`
  1647   1656   	    UNSHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}.a'
  1648   1657   	    SHARED_LIB_SUFFIX='${TCL_TRIM_DOTS}\$\{DBGX\}.so.1'
  1649   1658   	    TCL_LIB_VERSIONS_OK=nodots
  1650   1659   	    ;;
  1651   1660   	Darwin-*)
  1652   1661   	    CFLAGS_OPTIMIZE="-Os"
  1653   1662   	    SHLIB_CFLAGS="-fno-common"
................................................................................
  1701   1710   		hold_ldflags=$LDFLAGS
  1702   1711   		LDFLAGS="$LDFLAGS -dynamiclib -Wl,-single_module"
  1703   1712   		AC_TRY_LINK(, [int i;], tcl_cv_ld_single_module=yes, tcl_cv_ld_single_module=no)
  1704   1713   		LDFLAGS=$hold_ldflags])
  1705   1714   	    AS_IF([test $tcl_cv_ld_single_module = yes], [
  1706   1715   		SHLIB_LD="${SHLIB_LD} -Wl,-single_module"
  1707   1716   	    ])
  1708         -	    # TEA specific: link shlib with current and compatiblity version flags
         1717  +	    # TEA specific: link shlib with current and compatibility version flags
  1709   1718   	    vers=`echo ${PACKAGE_VERSION} | sed -e 's/^\([[0-9]]\{1,5\}\)\(\(\.[[0-9]]\{1,3\}\)\{0,2\}\).*$/\1\2/p' -e d`
  1710   1719   	    SHLIB_LD="${SHLIB_LD} -current_version ${vers:-0} -compatibility_version ${vers:-0}"
  1711   1720   	    SHLIB_SUFFIX=".dylib"
  1712   1721   	    # Don't use -prebind when building for Mac OS X 10.4 or later only:
  1713   1722   	    AS_IF([test "`echo "${MACOSX_DEPLOYMENT_TARGET}" | awk -F '10\\.' '{print int([$]2)}'`" -lt 4 -a \
  1714   1723   		"`echo "${CPPFLAGS}" | awk -F '-mmacosx-version-min=10\\.' '{print int([$]2)}'`" -lt 4], [
  1715   1724   		LDFLAGS="$LDFLAGS -prebind"])
................................................................................
  1937   1946   		    *)
  1938   1947   			SHLIB_LD='/usr/ccs/bin/ld -G -z text';;
  1939   1948   		esac
  1940   1949   		CC_SEARCH_FLAGS='-Wl,-R,${LIB_RUNTIME_DIR}'
  1941   1950   		LD_SEARCH_FLAGS='-R ${LIB_RUNTIME_DIR}'
  1942   1951   	    ])
  1943   1952   	    ;;
         1953  +	UNIX_SV* | UnixWare-5*)
         1954  +	    SHLIB_CFLAGS="-KPIC"
         1955  +	    SHLIB_LD='${CC} -G'
         1956  +	    SHLIB_LD_LIBS=""
         1957  +	    SHLIB_SUFFIX=".so"
         1958  +	    # Some UNIX_SV* systems (unixware 1.1.2 for example) have linkers
         1959  +	    # that don't grok the -Bexport option.  Test that it does.
         1960  +	    AC_CACHE_CHECK([for ld accepts -Bexport flag], tcl_cv_ld_Bexport, [
         1961  +		hold_ldflags=$LDFLAGS
         1962  +		LDFLAGS="$LDFLAGS -Wl,-Bexport"
         1963  +		AC_TRY_LINK(, [int i;], tcl_cv_ld_Bexport=yes, tcl_cv_ld_Bexport=no)
         1964  +	        LDFLAGS=$hold_ldflags])
         1965  +	    AS_IF([test $tcl_cv_ld_Bexport = yes], [
         1966  +		LDFLAGS="$LDFLAGS -Wl,-Bexport"
         1967  +	    ])
         1968  +	    CC_SEARCH_FLAGS=""
         1969  +	    LD_SEARCH_FLAGS=""
         1970  +	    ;;
  1944   1971       esac
  1945   1972   
  1946   1973       AS_IF([test "$do64bit" = yes -a "$do64bit_ok" = no], [
  1947   1974   	AC_MSG_WARN([64bit support being disabled -- don't know magic for this platform])
  1948   1975       ])
  1949   1976   
  1950   1977   dnl # Add any CPPFLAGS set in the environment to our CFLAGS, but delay doing so
................................................................................
  1961   1988       # libraries to the right flags for gcc, instead of those for the
  1962   1989       # standard manufacturer compiler.
  1963   1990   
  1964   1991       AS_IF([test "$GCC" = yes], [
  1965   1992   	case $system in
  1966   1993   	    AIX-*) ;;
  1967   1994   	    BSD/OS*) ;;
  1968         -	    CYGWIN_*) ;;
         1995  +	    CYGWIN_*|MINGW32_*) ;;
  1969   1996   	    IRIX*) ;;
  1970   1997   	    NetBSD-*|FreeBSD-*|OpenBSD-*) ;;
  1971   1998   	    Darwin-*) ;;
  1972   1999   	    SCO_SV-3.2*) ;;
  1973   2000   	    windows) ;;
  1974   2001   	    *) SHLIB_CFLAGS="-fPIC" ;;
  1975   2002   	esac])
  1976   2003   
  1977   2004       AS_IF([test "$tcl_cv_cc_visibility_hidden" != yes], [
  1978   2005   	AC_DEFINE(MODULE_SCOPE, [extern],
  1979   2006   	    [No Compiler support for module scope symbols])
  1980         -	AC_DEFINE(NO_VIZ)
  1981   2007       ])
  1982   2008   
  1983   2009       AS_IF([test "$SHARED_LIB_SUFFIX" = ""], [
  1984         -	# TEA specific: use PACKAGE_VERSION instead of VERSION
  1985         -	SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
         2010  +    # TEA specific: use PACKAGE_VERSION instead of VERSION
         2011  +    SHARED_LIB_SUFFIX='${PACKAGE_VERSION}${SHLIB_SUFFIX}'])
  1986   2012       AS_IF([test "$UNSHARED_LIB_SUFFIX" = ""], [
  1987         -	# TEA specific: use PACKAGE_VERSION instead of VERSION
  1988         -	UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
         2013  +    # TEA specific: use PACKAGE_VERSION instead of VERSION
         2014  +    UNSHARED_LIB_SUFFIX='${PACKAGE_VERSION}.a'])
         2015  +
         2016  +    if test "${GCC}" = "yes" -a ${SHLIB_SUFFIX} = ".dll"; then
         2017  +	AC_CACHE_CHECK(for SEH support in compiler,
         2018  +	    tcl_cv_seh,
         2019  +	AC_TRY_RUN([
         2020  +#define WIN32_LEAN_AND_MEAN
         2021  +#include <windows.h>
         2022  +#undef WIN32_LEAN_AND_MEAN
         2023  +
         2024  +	    int main(int argc, char** argv) {
         2025  +		int a, b = 0;
         2026  +		__try {
         2027  +		    a = 666 / b;
         2028  +		}
         2029  +		__except (EXCEPTION_EXECUTE_HANDLER) {
         2030  +		    return 0;
         2031  +		}
         2032  +		return 1;
         2033  +	    }
         2034  +	],
         2035  +	    tcl_cv_seh=yes,
         2036  +	    tcl_cv_seh=no,
         2037  +	    tcl_cv_seh=no)
         2038  +	)
         2039  +	if test "$tcl_cv_seh" = "no" ; then
         2040  +	    AC_DEFINE(HAVE_NO_SEH, 1,
         2041  +		    [Defined when mingw does not support SEH])
         2042  +	fi
         2043  +
         2044  +	#
         2045  +	# Check to see if the excpt.h include file provided contains the
         2046  +	# definition for EXCEPTION_DISPOSITION; if not, which is the case
         2047  +	# with Cygwin's version as of 2002-04-10, define it to be int,
         2048  +	# sufficient for getting the current code to work.
         2049  +	#
         2050  +	AC_CACHE_CHECK(for EXCEPTION_DISPOSITION support in include files,
         2051  +	    tcl_cv_eh_disposition,
         2052  +	    AC_TRY_COMPILE([
         2053  +#	    define WIN32_LEAN_AND_MEAN
         2054  +#	    include <windows.h>
         2055  +#	    undef WIN32_LEAN_AND_MEAN
         2056  +	    ],[
         2057  +		EXCEPTION_DISPOSITION x;
         2058  +	    ],
         2059  +		tcl_cv_eh_disposition=yes,
         2060  +		tcl_cv_eh_disposition=no)
         2061  +	)
         2062  +	if test "$tcl_cv_eh_disposition" = "no" ; then
         2063  +	AC_DEFINE(EXCEPTION_DISPOSITION, int,
         2064  +		[Defined when cygwin/mingw does not support EXCEPTION DISPOSITION])
         2065  +	fi
         2066  +
         2067  +	# Check to see if winnt.h defines CHAR, SHORT, and LONG
         2068  +	# even if VOID has already been #defined. The win32api
         2069  +	# used by mingw and cygwin is known to do this.
         2070  +
         2071  +	AC_CACHE_CHECK(for winnt.h that ignores VOID define,
         2072  +	    tcl_cv_winnt_ignore_void,
         2073  +	    AC_TRY_COMPILE([
         2074  +#define VOID void
         2075  +#define WIN32_LEAN_AND_MEAN
         2076  +#include <windows.h>
         2077  +#undef WIN32_LEAN_AND_MEAN
         2078  +	    ], [
         2079  +		CHAR c;
         2080  +		SHORT s;
         2081  +		LONG l;
         2082  +	    ],
         2083  +        tcl_cv_winnt_ignore_void=yes,
         2084  +        tcl_cv_winnt_ignore_void=no)
         2085  +	)
         2086  +	if test "$tcl_cv_winnt_ignore_void" = "yes" ; then
         2087  +	    AC_DEFINE(HAVE_WINNT_IGNORE_VOID, 1,
         2088  +		    [Defined when cygwin/mingw ignores VOID define in winnt.h])
         2089  +	fi
         2090  +    fi
         2091  +
         2092  +	# See if the compiler supports casting to a union type.
         2093  +	# This is used to stop gcc from printing a compiler
         2094  +	# warning when initializing a union member.
         2095  +
         2096  +	AC_CACHE_CHECK(for cast to union support,
         2097  +	    tcl_cv_cast_to_union,
         2098  +	    AC_TRY_COMPILE([],
         2099  +	    [
         2100  +		  union foo { int i; double d; };
         2101  +		  union foo f = (union foo) (int) 0;
         2102  +	    ],
         2103  +	    tcl_cv_cast_to_union=yes,
         2104  +	    tcl_cv_cast_to_union=no)
         2105  +	)
         2106  +	if test "$tcl_cv_cast_to_union" = "yes"; then
         2107  +	    AC_DEFINE(HAVE_CAST_TO_UNION, 1,
         2108  +		    [Defined when compiler supports casting to union type.])
         2109  +	fi
  1989   2110   
  1990   2111       AC_SUBST(CFLAGS_DEBUG)
  1991   2112       AC_SUBST(CFLAGS_OPTIMIZE)
  1992   2113       AC_SUBST(CFLAGS_WARNING)
  1993   2114   
  1994   2115       AC_SUBST(STLIB_LD)
  1995   2116       AC_SUBST(SHLIB_LD)
................................................................................
  2020   2141   # Results:
  2021   2142   #
  2022   2143   #	Defines only one of the following vars:
  2023   2144   #		HAVE_SYS_MODEM_H
  2024   2145   #		USE_TERMIOS
  2025   2146   #		USE_TERMIO
  2026   2147   #		USE_SGTTY
  2027         -#
  2028   2148   #--------------------------------------------------------------------
  2029   2149   
  2030   2150   AC_DEFUN([TEA_SERIAL_PORT], [
  2031   2151       AC_CHECK_HEADERS(sys/modem.h)
  2032   2152       AC_CACHE_CHECK([termios vs. termio vs. sgtty], tcl_cv_api_serial, [
  2033   2153       AC_TRY_RUN([
  2034   2154   #include <termios.h>
................................................................................
  2232   2352   #
  2233   2353   # Results:
  2234   2354   #
  2235   2355   #	Sets the following vars:
  2236   2356   #		XINCLUDES
  2237   2357   #		XLIBSW
  2238   2358   #		PKG_LIBS (appends to)
  2239         -#
  2240   2359   #--------------------------------------------------------------------
  2241   2360   
  2242   2361   AC_DEFUN([TEA_PATH_X], [
  2243   2362       if test "${TEA_WINDOWINGSYSTEM}" = "x11" ; then
  2244   2363   	TEA_PATH_UNIX_X
  2245   2364       fi
  2246   2365   ])
  2247   2366   
  2248   2367   AC_DEFUN([TEA_PATH_UNIX_X], [
  2249   2368       AC_PATH_X
  2250   2369       not_really_there=""
  2251   2370       if test "$no_x" = ""; then
  2252   2371   	if test "$x_includes" = ""; then
  2253         -	    AC_TRY_CPP([#include <X11/XIntrinsic.h>], , not_really_there="yes")
         2372  +	    AC_TRY_CPP([#include <X11/Xlib.h>], , not_really_there="yes")
  2254   2373   	else
  2255         -	    if test ! -r $x_includes/X11/Intrinsic.h; then
         2374  +	    if test ! -r $x_includes/X11/Xlib.h; then
  2256   2375   		not_really_there="yes"
  2257   2376   	    fi
  2258   2377   	fi
  2259   2378       fi
  2260   2379       if test "$no_x" = "yes" -o "$not_really_there" = "yes"; then
  2261   2380   	AC_MSG_CHECKING([for X11 header files])
  2262   2381   	found_xincludes="no"
  2263         -	AC_TRY_CPP([#include <X11/Intrinsic.h>], found_xincludes="yes", found_xincludes="no")
         2382  +	AC_TRY_CPP([#include <X11/Xlib.h>], found_xincludes="yes", found_xincludes="no")
  2264   2383   	if test "$found_xincludes" = "no"; then
  2265   2384   	    dirs="/usr/unsupported/include /usr/local/include /usr/X386/include /usr/X11R6/include /usr/X11R5/include /usr/include/X11R5 /usr/include/X11R4 /usr/openwin/include /usr/X11/include /usr/sww/include"
  2266   2385   	    for i in $dirs ; do
  2267         -		if test -r $i/X11/Intrinsic.h; then
         2386  +		if test -r $i/X11/Xlib.h; then
  2268   2387   		    AC_MSG_RESULT([$i])
  2269   2388   		    XINCLUDES=" -I$i"
  2270   2389   		    found_xincludes="yes"
  2271   2390   		    break
  2272   2391   		fi
  2273   2392   	    done
  2274   2393   	fi
................................................................................
  2328   2447   # Results:
  2329   2448   #
  2330   2449   #	Defines some of the following vars:
  2331   2450   #		HAVE_SYS_IOCTL_H
  2332   2451   #		HAVE_SYS_FILIO_H
  2333   2452   #		USE_FIONBIO
  2334   2453   #		O_NONBLOCK
  2335         -#
  2336   2454   #--------------------------------------------------------------------
  2337   2455   
  2338   2456   AC_DEFUN([TEA_BLOCKING_STYLE], [
  2339   2457       AC_CHECK_HEADERS(sys/ioctl.h)
  2340   2458       AC_CHECK_HEADERS(sys/filio.h)
  2341   2459       TEA_CONFIG_SYSTEM
  2342   2460       AC_MSG_CHECKING([FIONBIO vs. O_NONBLOCK for nonblocking I/O])
................................................................................
  2363   2481   # Results:
  2364   2482   #
  2365   2483   #	Defines some of the following vars:
  2366   2484   #		USE_DELTA_FOR_TZ
  2367   2485   #		HAVE_TM_GMTOFF
  2368   2486   #		HAVE_TM_TZADJ
  2369   2487   #		HAVE_TIMEZONE_VAR
  2370         -#
  2371   2488   #--------------------------------------------------------------------
  2372   2489   
  2373   2490   AC_DEFUN([TEA_TIME_HANDLER], [
  2374   2491       AC_CHECK_HEADERS(sys/time.h)
  2375   2492       AC_HEADER_TIME
  2376   2493       AC_STRUCT_TIMEZONE
  2377   2494   
................................................................................
  2432   2549   # Arguments:
  2433   2550   #	none
  2434   2551   #
  2435   2552   # Results:
  2436   2553   #
  2437   2554   #	Might defines some of the following vars:
  2438   2555   #		strtod (=fixstrtod)
  2439         -#
  2440   2556   #--------------------------------------------------------------------
  2441   2557   
  2442   2558   AC_DEFUN([TEA_BUGGY_STRTOD], [
  2443   2559       AC_CHECK_FUNC(strtod, tcl_strtod=1, tcl_strtod=0)
  2444   2560       if test "$tcl_strtod" = 1; then
  2445   2561   	AC_CACHE_CHECK([for Solaris2.4/Tru64 strtod bugs], tcl_cv_strtod_buggy,[
  2446   2562   	    AC_TRY_RUN([
................................................................................
  2483   2599   #	Requires the following vars to be set in the Makefile:
  2484   2600   #		DL_LIBS (not in TEA, only needed in core)
  2485   2601   #		LIBS
  2486   2602   #		MATH_LIBS
  2487   2603   #
  2488   2604   # Results:
  2489   2605   #
  2490         -#	Subst's the following var:
         2606  +#	Substitutes the following vars:
  2491   2607   #		TCL_LIBS
  2492   2608   #		MATH_LIBS
  2493   2609   #
  2494   2610   #	Might append to the following vars:
  2495   2611   #		LIBS
  2496   2612   #
  2497   2613   #	Might define the following vars:
  2498   2614   #		HAVE_NET_ERRNO_H
  2499         -#
  2500   2615   #--------------------------------------------------------------------
  2501   2616   
  2502   2617   AC_DEFUN([TEA_TCL_LINK_LIBS], [
  2503   2618       #--------------------------------------------------------------------
  2504   2619       # On a few very rare systems, all of the libm.a stuff is
  2505   2620       # already in libc.a.  Set compiler flags accordingly.
  2506   2621       # Also, Linux requires the "ieee" library for math to work
................................................................................
  2570   2685   #
  2571   2686   # Results:
  2572   2687   #
  2573   2688   #	Might define the following vars:
  2574   2689   #		_ISOC99_SOURCE
  2575   2690   #		_LARGEFILE64_SOURCE
  2576   2691   #		_LARGEFILE_SOURCE64
  2577         -#
  2578   2692   #--------------------------------------------------------------------
  2579   2693   
  2580   2694   AC_DEFUN([TEA_TCL_EARLY_FLAG],[
  2581   2695       AC_CACHE_VAL([tcl_cv_flag_]translit($1,[A-Z],[a-z]),
  2582   2696   	AC_TRY_COMPILE([$2], $3, [tcl_cv_flag_]translit($1,[A-Z],[a-z])=no,
  2583   2697   	    AC_TRY_COMPILE([[#define ]$1[ 1
  2584   2698   ]$2], $3,
................................................................................
  2618   2732   #
  2619   2733   #	Might define the following vars:
  2620   2734   #		TCL_WIDE_INT_IS_LONG
  2621   2735   #		TCL_WIDE_INT_TYPE
  2622   2736   #		HAVE_STRUCT_DIRENT64
  2623   2737   #		HAVE_STRUCT_STAT64
  2624   2738   #		HAVE_TYPE_OFF64_T
  2625         -#
  2626   2739   #--------------------------------------------------------------------
  2627   2740   
  2628   2741   AC_DEFUN([TEA_TCL_64BIT_FLAGS], [
  2629   2742       AC_MSG_CHECKING([for 64-bit integer type])
  2630   2743       AC_CACHE_VAL(tcl_cv_type_64bit,[
  2631   2744   	tcl_cv_type_64bit=none
  2632   2745   	# See if the compiler knows natively about __int64
................................................................................
  2650   2763   	AC_DEFINE_UNQUOTED(TCL_WIDE_INT_TYPE,${tcl_cv_type_64bit},
  2651   2764   	    [What type should be used to define wide integers?])
  2652   2765   	AC_MSG_RESULT([${tcl_cv_type_64bit}])
  2653   2766   
  2654   2767   	# Now check for auxiliary declarations
  2655   2768   	AC_CACHE_CHECK([for struct dirent64], tcl_cv_struct_dirent64,[
  2656   2769   	    AC_TRY_COMPILE([#include <sys/types.h>
  2657         -#include <sys/dirent.h>],[struct dirent64 p;],
         2770  +#include <dirent.h>],[struct dirent64 p;],
  2658   2771   		tcl_cv_struct_dirent64=yes,tcl_cv_struct_dirent64=no)])
  2659   2772   	if test "x${tcl_cv_struct_dirent64}" = "xyes" ; then
  2660   2773   	    AC_DEFINE(HAVE_STRUCT_DIRENT64, 1, [Is 'struct dirent64' in <sys/types.h>?])
  2661   2774   	fi
  2662   2775   
  2663   2776   	AC_CACHE_CHECK([for struct stat64], tcl_cv_struct_stat64,[
  2664   2777   	    AC_TRY_COMPILE([#include <sys/stat.h>],[struct stat64 p;
................................................................................
  2735   2848   	AC_MSG_ERROR([
  2736   2849   TEA version not specified.])
  2737   2850       elif test "$1" != "${TEA_VERSION}" ; then
  2738   2851   	AC_MSG_RESULT([warning: requested TEA version "$1", have "${TEA_VERSION}"])
  2739   2852       else
  2740   2853   	AC_MSG_RESULT([ok (TEA ${TEA_VERSION})])
  2741   2854       fi
         2855  +
         2856  +    # If the user did not set CFLAGS, set it now to keep macros
         2857  +    # like AC_PROG_CC and AC_TRY_COMPILE from adding "-g -O2".
         2858  +    if test "${CFLAGS+set}" != "set" ; then
         2859  +	CFLAGS=""
         2860  +    fi
         2861  +
  2742   2862       case "`uname -s`" in
  2743   2863   	*win32*|*WIN32*|*MINGW32_*)
  2744   2864   	    AC_CHECK_PROG(CYGPATH, cygpath, cygpath -w, echo)
  2745   2865   	    EXEEXT=".exe"
  2746   2866   	    TEA_PLATFORM="windows"
  2747   2867   	    ;;
  2748   2868   	*CYGWIN_*)
  2749   2869   	    CYGPATH=echo
  2750   2870   	    EXEEXT=".exe"
  2751   2871   	    # TEA_PLATFORM is determined later in LOAD_TCLCONFIG
  2752   2872   	    ;;
  2753   2873   	*)
  2754   2874   	    CYGPATH=echo
  2755         -	    EXEEXT=""
  2756         -	    TEA_PLATFORM="unix"
         2875  +	    # Maybe we are cross-compiling....
         2876  +	    case ${host_alias} in
         2877  +		*mingw32*)
         2878  +		EXEEXT=".exe"
         2879  +		TEA_PLATFORM="windows"
         2880  +		;;
         2881  +	    *)
         2882  +		EXEEXT=""
         2883  +		TEA_PLATFORM="unix"
         2884  +		;;
         2885  +	    esac
  2757   2886   	    ;;
  2758   2887       esac
  2759   2888   
  2760   2889       # Check if exec_prefix is set. If not use fall back to prefix.
  2761   2890       # Note when adjusted, so that TEA_PREFIX can correct for this.
  2762   2891       # This is needed for recursive configures, since autoconf propagates
  2763   2892       # $prefix, but not $exec_prefix (doh!).
  2764   2893       if test x$exec_prefix = xNONE ; then
  2765   2894   	exec_prefix_default=yes
  2766   2895   	exec_prefix=$prefix
  2767   2896       fi
         2897  +
         2898  +    AC_MSG_NOTICE([configuring ${PACKAGE_NAME} ${PACKAGE_VERSION}])
  2768   2899   
  2769   2900       AC_SUBST(EXEEXT)
  2770   2901       AC_SUBST(CYGPATH)
  2771   2902   
  2772   2903       # This package name must be replaced statically for AC_SUBST to work
  2773   2904       AC_SUBST(PKG_LIB_FILE)
  2774   2905       # Substitute STUB_LIB_FILE in case package creates a stub library too.
................................................................................
  2996   3127   #	Defines and substs the following vars:
  2997   3128   #		PKG_CFLAGS
  2998   3129   #------------------------------------------------------------------------
  2999   3130   AC_DEFUN([TEA_ADD_CFLAGS], [
  3000   3131       PKG_CFLAGS="$PKG_CFLAGS $@"
  3001   3132       AC_SUBST(PKG_CFLAGS)
  3002   3133   ])
         3134  +
         3135  +#------------------------------------------------------------------------
         3136  +# TEA_ADD_CLEANFILES --
         3137  +#
         3138  +#	Specify one or more CLEANFILES.
         3139  +#
         3140  +# Arguments:
         3141  +#	one or more file names to clean target
         3142  +#
         3143  +# Results:
         3144  +#
         3145  +#	Appends to CLEANFILES, already defined for subst in LOAD_TCLCONFIG
         3146  +#------------------------------------------------------------------------
         3147  +AC_DEFUN([TEA_ADD_CLEANFILES], [
         3148  +    CLEANFILES="$CLEANFILES $@"
         3149  +])
  3003   3150   
  3004   3151   #------------------------------------------------------------------------
  3005   3152   # TEA_PREFIX --
  3006   3153   #
  3007   3154   #	Handle the --prefix=... option by defaulting to what Tcl gave
  3008   3155   #
  3009   3156   # Arguments:
................................................................................
  3051   3198   #
  3052   3199   #	Sets up CC var and other standard bits we need to make executables.
  3053   3200   #------------------------------------------------------------------------
  3054   3201   AC_DEFUN([TEA_SETUP_COMPILER_CC], [
  3055   3202       # Don't put any macros that use the compiler (e.g. AC_TRY_COMPILE)
  3056   3203       # in this macro, they need to go into TEA_SETUP_COMPILER instead.
  3057   3204   
  3058         -    # If the user did not set CFLAGS, set it now to keep
  3059         -    # the AC_PROG_CC macro from adding "-g -O2".
  3060         -    if test "${CFLAGS+set}" != "set" ; then
  3061         -	CFLAGS=""
  3062         -    fi
  3063         -
  3064   3205       AC_PROG_CC
  3065   3206       AC_PROG_CPP
  3066   3207   
  3067         -    AC_PROG_INSTALL
         3208  +    INSTALL="\$(SHELL) \$(srcdir)/tclconfig/install-sh -c"
         3209  +    AC_SUBST(INSTALL)
         3210  +    INSTALL_DATA="\${INSTALL} -m 644"
         3211  +    AC_SUBST(INSTALL_DATA)
         3212  +    INSTALL_PROGRAM="\${INSTALL}"
         3213  +    AC_SUBST(INSTALL_PROGRAM)
         3214  +    INSTALL_SCRIPT="\${INSTALL}"
         3215  +    AC_SUBST(INSTALL_SCRIPT)
  3068   3216   
  3069   3217       #--------------------------------------------------------------------
  3070   3218       # Checks to see if the make program sets the $MAKE variable.
  3071   3219       #--------------------------------------------------------------------
  3072   3220   
  3073   3221       AC_PROG_MAKE_SET
  3074   3222   
  3075   3223       #--------------------------------------------------------------------
  3076   3224       # Find ranlib
  3077   3225       #--------------------------------------------------------------------
  3078   3226   
  3079         -    AC_PROG_RANLIB
         3227  +    AC_CHECK_TOOL(RANLIB, ranlib)
  3080   3228   
  3081   3229       #--------------------------------------------------------------------
  3082   3230       # Determines the correct binary file extension (.o, .obj, .exe etc.)
  3083   3231       #--------------------------------------------------------------------
  3084   3232   
  3085   3233       AC_OBJEXT
  3086   3234       AC_EXEEXT
................................................................................
  3151   3299   #	CFLAGS -	Done late here to note disturb other AC macros
  3152   3300   #       MAKE_LIB -      Command to execute to build the Tcl library;
  3153   3301   #                       differs depending on whether or not Tcl is being
  3154   3302   #                       compiled as a shared library.
  3155   3303   #	MAKE_SHARED_LIB	Makefile rule for building a shared library
  3156   3304   #	MAKE_STATIC_LIB	Makefile rule for building a static library
  3157   3305   #	MAKE_STUB_LIB	Makefile rule for building a stub library
         3306  +#	VC_MANIFEST_EMBED_DLL Makefile rule for embedded VC manifest in DLL
         3307  +#	VC_MANIFEST_EMBED_EXE Makefile rule for embedded VC manifest in EXE
  3158   3308   #------------------------------------------------------------------------
  3159   3309   
  3160   3310   AC_DEFUN([TEA_MAKE_LIB], [
  3161   3311       if test "${TEA_PLATFORM}" = "windows" -a "$GCC" != "yes"; then
  3162   3312   	MAKE_STATIC_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_OBJECTS)"
  3163   3313   	MAKE_SHARED_LIB="\${SHLIB_LD} \${SHLIB_LD_LIBS} \${LDFLAGS_DEFAULT} -out:\[$]@ \$(PKG_OBJECTS)"
  3164         -	MAKE_STUB_LIB="\${STLIB_LD} -out:\[$]@ \$(PKG_STUB_OBJECTS)"
         3314  +	AC_EGREP_CPP([manifest needed], [
         3315  +#if defined(_MSC_VER) && _MSC_VER >= 1400
         3316  +print("manifest needed")
         3317  +#endif
         3318  +	], [
         3319  +	# Could do a CHECK_PROG for mt, but should always be with MSVC8+
         3320  +	VC_MANIFEST_EMBED_DLL="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;2 ; fi"
         3321  +	VC_MANIFEST_EMBED_EXE="if test -f \[$]@.manifest ; then mt.exe -nologo -manifest \[$]@.manifest -outputresource:\[$]@\;1 ; fi"
         3322  +	MAKE_SHARED_LIB="${MAKE_SHARED_LIB} ; ${VC_MANIFEST_EMBED_DLL}"
         3323  +	TEA_ADD_CLEANFILES([*.manifest])
         3324  +	])
         3325  +	MAKE_STUB_LIB="\${STLIB_LD} -nodefaultlib -out:\[$]@ \$(PKG_STUB_OBJECTS)"
  3165   3326       else
  3166   3327   	MAKE_STATIC_LIB="\${STLIB_LD} \[$]@ \$(PKG_OBJECTS)"
  3167   3328   	MAKE_SHARED_LIB="\${SHLIB_LD} -o \[$]@ \$(PKG_OBJECTS) \${SHLIB_LD_LIBS}"
  3168   3329   	MAKE_STUB_LIB="\${STLIB_LD} \[$]@ \$(PKG_STUB_OBJECTS)"
  3169   3330       fi
  3170   3331   
  3171   3332       if test "${SHARED_BUILD}" = "1" ; then
................................................................................
  3180   3341       # substituted. (@@@ Might not be necessary anymore)
  3181   3342       #--------------------------------------------------------------------
  3182   3343   
  3183   3344       if test "${TEA_PLATFORM}" = "windows" ; then
  3184   3345   	if test "${SHARED_BUILD}" = "1" ; then
  3185   3346   	    # We force the unresolved linking of symbols that are really in
  3186   3347   	    # the private libraries of Tcl and Tk.
  3187         -	    SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
  3188   3348   	    if test x"${TK_BIN_DIR}" != x ; then
  3189   3349   		SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TK_BIN_DIR}/${TK_STUB_LIB_FILE}`\""
         3350  +	    fi
         3351  +	    SHLIB_LD_LIBS="${SHLIB_LD_LIBS} \"`${CYGPATH} ${TCL_BIN_DIR}/${TCL_STUB_LIB_FILE}`\""
         3352  +	    if test "$GCC" = "yes"; then
         3353  +		SHLIB_LD_LIBS="${SHLIB_LD_LIBS} -static-libgcc"
  3190   3354   	    fi
  3191   3355   	    eval eval "PKG_LIB_FILE=${PACKAGE_NAME}${SHARED_LIB_SUFFIX}"
  3192   3356   	else
  3193   3357   	    eval eval "PKG_LIB_FILE=${PACKAGE_NAME}${UNSHARED_LIB_SUFFIX}"
         3358  +	    if test "$GCC" = "yes"; then
         3359  +		PKG_LIB_FILE=lib${PKG_LIB_FILE}
         3360  +	    fi
  3194   3361   	fi
  3195   3362   	# Some packages build their own stubs libraries
  3196   3363   	eval eval "PKG_STUB_LIB_FILE=${PACKAGE_NAME}stub${UNSHARED_LIB_SUFFIX}"
  3197   3364   	if test "$GCC" = "yes"; then
  3198   3365   	    PKG_STUB_LIB_FILE=lib${PKG_STUB_LIB_FILE}
  3199   3366   	fi
  3200   3367   	# These aren't needed on Windows (either MSVC or gcc)
................................................................................
  3224   3391       fi
  3225   3392   
  3226   3393       AC_SUBST(MAKE_LIB)
  3227   3394       AC_SUBST(MAKE_SHARED_LIB)
  3228   3395       AC_SUBST(MAKE_STATIC_LIB)
  3229   3396       AC_SUBST(MAKE_STUB_LIB)
  3230   3397       AC_SUBST(RANLIB_STUB)
         3398  +    AC_SUBST(VC_MANIFEST_EMBED_DLL)
         3399  +    AC_SUBST(VC_MANIFEST_EMBED_EXE)
  3231   3400   ])
  3232   3401   
  3233   3402   #------------------------------------------------------------------------
  3234   3403   # TEA_LIB_SPEC --
  3235   3404   #
  3236   3405   #	Compute the name of an existing object library located in libdir
  3237   3406   #	from the given base name and produce the appropriate linker flags.
................................................................................
  3312   3481   #
  3313   3482   #	Requires:
  3314   3483   #		TCL_SRC_DIR	Assumes that TEA_LOAD_TCLCONFIG has
  3315   3484   #				already been called.
  3316   3485   #
  3317   3486   # Results:
  3318   3487   #
  3319         -#	Substs the following vars:
         3488  +#	Substitutes the following vars:
  3320   3489   #		TCL_TOP_DIR_NATIVE
  3321   3490   #		TCL_INCLUDES
  3322   3491   #------------------------------------------------------------------------
  3323   3492   
  3324   3493   AC_DEFUN([TEA_PRIVATE_TCL_HEADERS], [
  3325   3494       # Allow for --with-tclinclude to take effect and define ${ac_cv_c_tclh}
  3326   3495       AC_REQUIRE([TEA_PUBLIC_TCL_HEADERS])
................................................................................
  3390   3559   #	CYGPATH must be set
  3391   3560   #
  3392   3561   # Results:
  3393   3562   #
  3394   3563   #	Adds a --with-tclinclude switch to configure.
  3395   3564   #	Result is cached.
  3396   3565   #
  3397         -#	Substs the following vars:
         3566  +#	Substitutes the following vars:
  3398   3567   #		TCL_INCLUDES
  3399   3568   #------------------------------------------------------------------------
  3400   3569   
  3401   3570   AC_DEFUN([TEA_PUBLIC_TCL_HEADERS], [
  3402   3571       AC_MSG_CHECKING([for Tcl public headers])
  3403   3572   
  3404   3573       AC_ARG_WITH(tclinclude, [  --with-tclinclude       directory containing the public Tcl header files], with_tclinclude=${withval})
................................................................................
  3480   3649   #
  3481   3650   #	Requires:
  3482   3651   #		TK_SRC_DIR	Assumes that TEA_LOAD_TKCONFIG has
  3483   3652   #				 already been called.
  3484   3653   #
  3485   3654   # Results:
  3486   3655   #
  3487         -#	Substs the following vars:
         3656  +#	Substitutes the following vars:
  3488   3657   #		TK_INCLUDES
  3489   3658   #------------------------------------------------------------------------
  3490   3659   
  3491   3660   AC_DEFUN([TEA_PRIVATE_TK_HEADERS], [
  3492   3661       # Allow for --with-tkinclude to take effect and define ${ac_cv_c_tkh}
  3493   3662       AC_REQUIRE([TEA_PUBLIC_TK_HEADERS])
  3494   3663       AC_MSG_CHECKING([for Tk private include files])
................................................................................
  3569   3738   #	CYGPATH must be set
  3570   3739   #
  3571   3740   # Results:
  3572   3741   #
  3573   3742   #	Adds a --with-tkinclude switch to configure.
  3574   3743   #	Result is cached.
  3575   3744   #
  3576         -#	Substs the following vars:
         3745  +#	Substitutes the following vars:
  3577   3746   #		TK_INCLUDES
  3578   3747   #------------------------------------------------------------------------
  3579   3748   
  3580   3749   AC_DEFUN([TEA_PUBLIC_TK_HEADERS], [
  3581   3750       AC_MSG_CHECKING([for Tk public headers])
  3582   3751   
  3583   3752       AC_ARG_WITH(tkinclude, [  --with-tkinclude        directory containing the public Tk header files], with_tkinclude=${withval})
................................................................................
  3787   3956   # Arguments:
  3788   3957   #
  3789   3958   #	Requires the following vars to be set:
  3790   3959   #		$1_BIN_DIR
  3791   3960   #
  3792   3961   # Results:
  3793   3962   #
  3794         -#	Subst the following vars:
         3963  +#	Substitutes the following vars:
  3795   3964   #		$1_SRC_DIR
  3796   3965   #		$1_LIB_FILE
  3797   3966   #		$1_LIB_SPEC
  3798         -#
  3799   3967   #------------------------------------------------------------------------
  3800   3968   
  3801   3969   AC_DEFUN([TEA_LOAD_CONFIG], [
  3802   3970       AC_MSG_CHECKING([for existence of ${$1_BIN_DIR}/$1Config.sh])
  3803   3971   
  3804   3972       if test -f "${$1_BIN_DIR}/$1Config.sh" ; then
  3805   3973           AC_MSG_RESULT([loading])
................................................................................
  3818   3986       #
  3819   3987   
  3820   3988       if test -f "${$1_BIN_DIR}/Makefile" ; then
  3821   3989   	AC_MSG_WARN([Found Makefile - using build library specs for $1])
  3822   3990           $1_LIB_SPEC=${$1_BUILD_LIB_SPEC}
  3823   3991           $1_STUB_LIB_SPEC=${$1_BUILD_STUB_LIB_SPEC}
  3824   3992           $1_STUB_LIB_PATH=${$1_BUILD_STUB_LIB_PATH}
         3993  +        $1_INCLUDE_SPEC=${$1_BUILD_INCLUDE_SPEC}
         3994  +        $1_LIBRARY_PATH=${$1_LIBRARY_PATH}
  3825   3995       fi
  3826   3996   
  3827   3997       AC_SUBST($1_VERSION)
  3828   3998       AC_SUBST($1_BIN_DIR)
  3829   3999       AC_SUBST($1_SRC_DIR)
  3830   4000   
  3831   4001       AC_SUBST($1_LIB_FILE)
................................................................................
  3850   4020   # TEA_LOAD_CONFIG_LIB --
  3851   4021   #
  3852   4022   #	Helper function to load correct library from another extension's
  3853   4023   #	${PACKAGE}Config.sh.
  3854   4024   #
  3855   4025   # Results:
  3856   4026   #	Adds to LIBS the appropriate extension library
  3857         -#
  3858   4027   #------------------------------------------------------------------------
  3859   4028   AC_DEFUN([TEA_LOAD_CONFIG_LIB], [
  3860   4029       AC_MSG_CHECKING([For $1 library for LIBS])
  3861   4030       # This simplifies the use of stub libraries by automatically adding
  3862   4031       # the stub lib to your path.  Normally this would add to SHLIB_LD_LIBS,
  3863   4032       # but this is called before CONFIG_CFLAGS.  More importantly, this adds
  3864   4033       # to PKG_LIBS, which becomes LIBS, and that is only used by SHLIB_LD.
................................................................................
  3882   4051   #
  3883   4052   # Arguments:
  3884   4053   #
  3885   4054   #	Requires the following vars to be set:
  3886   4055   #		$1
  3887   4056   #
  3888   4057   # Results:
  3889         -#	Subst the following vars:
  3890         -#
         4058  +#	Substitutes the following vars:
  3891   4059   #------------------------------------------------------------------------
  3892   4060   
  3893         -AC_DEFUN(TEA_EXPORT_CONFIG, [
         4061  +AC_DEFUN([TEA_EXPORT_CONFIG], [
  3894   4062       #--------------------------------------------------------------------
  3895   4063       # These are for $1Config.sh
  3896   4064       #--------------------------------------------------------------------
  3897   4065   
  3898   4066       # pkglibdir must be a fully qualified path and (not ${exec_prefix}/lib)
  3899   4067       eval pkglibdir="[$]{libdir}/$1${PACKAGE_VERSION}"
  3900   4068       if test "${TCL_LIB_VERSIONS_OK}" = "ok"; then

Deleted mkdll.sh.

     1         -#!/bin/sh
     2         -#
     3         -# This script is used to compile SQLite into a DLL.
     4         -#
     5         -# Two separate DLLs are generated.  "sqlite3.dll" is the core
     6         -# library.  "tclsqlite3.dll" contains the TCL bindings and is the
     7         -# library that is loaded into TCL in order to run SQLite.
     8         -#
     9         -make sqlite3.c
    10         -PATH=$PATH:/opt/mingw/bin
    11         -TCLDIR=/home/drh/tcltk/846/win/846win
    12         -TCLSTUBLIB=$TCLDIR/libtcl84stub.a
    13         -OPTS='-DUSE_TCL_STUBS=1 -DBUILD_sqlite=1 -DSQLITE_OS_WIN=1'
    14         -OPTS="$OPTS -DSQLITE_THREADSAFE=1"
    15         -OPTS="$OPTS -DSQLITE_ENABLE_FTS3=1"
    16         -OPTS="$OPTS -DSQLITE_ENABLE_RTREE=1"
    17         -OPTS="$OPTS -DSQLITE_ENABLE_COLUMN_METADATA=1"
    18         -CC="i386-mingw32msvc-gcc -Os $OPTS -Itsrc -I$TCLDIR"
    19         -NM="i386-mingw32msvc-nm"
    20         -CMD="$CC -c sqlite3.c"
    21         -echo $CMD
    22         -$CMD
    23         -CMD="$CC -c tclsqlite3.c"
    24         -echo $CMD
    25         -$CMD
    26         -echo 'EXPORTS' >tclsqlite3.def
    27         -$NM tclsqlite3.o | grep ' T ' >temp1
    28         -grep '_Init$' temp1 >temp2
    29         -grep '_SafeInit$' temp1 >>temp2
    30         -grep ' T _sqlite3_' temp1 >>temp2
    31         -echo 'EXPORTS' >tclsqlite3.def
    32         -sed 's/^.* T _//' temp2 | sort | uniq >>tclsqlite3.def
    33         -i386-mingw32msvc-dllwrap \
    34         -     --def tclsqlite3.def -v --export-all \
    35         -     --driver-name i386-mingw32msvc-gcc \
    36         -     --dlltool-name i386-mingw32msvc-dlltool \
    37         -     --as i386-mingw32msvc-as \
    38         -     --target i386-mingw32 \
    39         -     -dllname tclsqlite3.dll -lmsvcrt tclsqlite3.o $TCLSTUBLIB
    40         -$NM sqlite3.o | grep ' T ' >temp1
    41         -echo 'EXPORTS' >sqlite3.def
    42         -grep ' _sqlite3_' temp1 | sed 's/^.* _//' >>sqlite3.def
    43         -i386-mingw32msvc-dllwrap \
    44         -     --def sqlite3.def -v --export-all \
    45         -     --driver-name i386-mingw32msvc-gcc \
    46         -     --dlltool-name i386-mingw32msvc-dlltool \
    47         -     --as i386-mingw32msvc-as \
    48         -     --target i386-mingw32 \
    49         -     -dllname sqlite3.dll -lmsvcrt sqlite3.o

Deleted mkextu.sh.

     1         -#!/bin/sh
     2         -#
     3         -# This script is used to compile SQLite into a shared library on Linux.
     4         -#
     5         -# Two separate shared libraries are generated.  "sqlite3.so" is the core
     6         -# library.  "tclsqlite3.so" contains the TCL bindings and is the
     7         -# library that is loaded into TCL in order to run SQLite.
     8         -#
     9         -CFLAGS=-O2 -Wall
    10         -make fts2amal.c
    11         -echo gcc $CFLAGS -shared fts2amal.c -o fts2.so
    12         -gcc $CFLAGS -shared fts2amal.c -o fts2.so
    13         -strip fts2.so

Deleted mkextw.sh.

     1         -#!/bin/sh
     2         -#
     3         -# This script is used to compile SQLite extensions into DLLs.
     4         -#
     5         -make fts2amal.c
     6         -PATH=$PATH:/opt/mingw/bin
     7         -OPTS='-DTHREADSAFE=1 -DBUILD_sqlite=1 -DSQLITE_OS_WIN=1'
     8         -CC="i386-mingw32msvc-gcc -O2 $OPTS -Itsrc"
     9         -NM="i386-mingw32msvc-nm"
    10         -CMD="$CC -c fts2amal.c"
    11         -echo $CMD
    12         -$CMD
    13         -echo 'EXPORTS' >fts2.def
    14         -echo 'sqlite3_fts2_init' >>fts2.def
    15         -i386-mingw32msvc-dllwrap \
    16         -     --def fts2.def -v --export-all \
    17         -     --driver-name i386-mingw32msvc-gcc \
    18         -     --dlltool-name i386-mingw32msvc-dlltool \
    19         -     --as i386-mingw32msvc-as \
    20         -     --target i386-mingw32 \
    21         -     -dllname fts2.dll -lmsvcrt fts2amal.o
    22         -zip fts2dll.zip fts2.dll fts2.def

Changes to src/alter.c.

    73     73         do {
    74     74           zCsr += len;
    75     75           len = sqlite3GetToken(zCsr, &token);
    76     76         } while( token==TK_SPACE );
    77     77         assert( len>0 );
    78     78       } while( token!=TK_LP && token!=TK_USING );
    79     79   
    80         -    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
    81         -       zTableName, tname.z+tname.n);
           80  +    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
           81  +       zSql, zTableName, tname.z+tname.n);
    82     82       sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
    83     83     }
    84     84   }
    85     85   
    86     86   /*
    87     87   ** This C function implements an SQL user function that is used by SQL code
    88     88   ** generated by the ALTER TABLE ... RENAME command to modify the definition
................................................................................
   126    126         }while( token==TK_SPACE );
   127    127   
   128    128         zParent = sqlite3DbStrNDup(db, (const char *)z, n);
   129    129         if( zParent==0 ) break;
   130    130         sqlite3Dequote(zParent);
   131    131         if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
   132    132           char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
   133         -            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
          133  +            (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
   134    134           );
   135    135           sqlite3DbFree(db, zOutput);
   136    136           zOutput = zOut;
   137    137           zInput = &z[n];
   138    138         }
   139    139         sqlite3DbFree(db, zParent);
   140    140       }
................................................................................
   212    212           dist = 0;
   213    213         }
   214    214       } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
   215    215   
   216    216       /* Variable tname now contains the token that is the old table-name
   217    217       ** in the CREATE TRIGGER statement.
   218    218       */
   219         -    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
   220         -       zTableName, tname.z+tname.n);
          219  +    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
          220  +       zSql, zTableName, tname.z+tname.n);
   221    221       sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
   222    222     }
   223    223   }
   224    224   #endif   /* !SQLITE_OMIT_TRIGGER */
   225    225   
   226    226   /*
   227    227   ** Register built-in functions used to help implement ALTER TABLE
................................................................................
   601    601       int r1 = sqlite3GetTempReg(pParse);
   602    602       int r2 = sqlite3GetTempReg(pParse);
   603    603       int j1;
   604    604       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
   605    605       sqlite3VdbeUsesBtree(v, iDb);
   606    606       sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
   607    607       j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
          608  +    sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
   608    609       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
   609    610       sqlite3VdbeJumpHere(v, j1);
   610    611       sqlite3ReleaseTempReg(pParse, r1);
   611    612       sqlite3ReleaseTempReg(pParse, r2);
   612    613     }
   613    614   }
   614    615   

Changes to src/analyze.c.

  1073   1073       **   Rewind csr
  1074   1074       **   if eof(csr) goto end_of_scan;
  1075   1075       **   regChng = 0
  1076   1076       **   goto next_push_0;
  1077   1077       **
  1078   1078       */
  1079   1079       addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
         1080  +    VdbeCoverage(v);
  1080   1081       sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  1081   1082       addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
  1082   1083   
  1083   1084       /*
  1084   1085       **  next_row:
  1085   1086       **   regChng = 0
  1086   1087       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
................................................................................
  1094   1095       for(i=0; i<nCol; i++){
  1095   1096         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  1096   1097         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  1097   1098         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  1098   1099         aGotoChng[i] = 
  1099   1100         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  1100   1101         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
         1102  +      VdbeCoverage(v);
  1101   1103       }
  1102   1104       sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
  1103   1105       aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
  1104   1106   
  1105   1107       /*
  1106   1108       **  chng_addr_0:
  1107   1109       **   regPrev(0) = idx(0)
................................................................................
  1140   1142         sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  1141   1143       }
  1142   1144   #endif
  1143   1145       assert( regChng==(regStat4+1) );
  1144   1146       sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  1145   1147       sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  1146   1148       sqlite3VdbeChangeP5(v, 2+IsStat34);
  1147         -    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
         1149  +    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  1148   1150   
  1149   1151       /* Add the entry to the stat1 table. */
  1150   1152       callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  1151   1153       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  1152   1154       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  1153   1155       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  1154   1156       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
................................................................................
  1167   1169         u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  1168   1170   
  1169   1171         pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
  1170   1172   
  1171   1173         addrNext = sqlite3VdbeCurrentAddr(v);
  1172   1174         callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  1173   1175         addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
         1176  +      VdbeCoverage(v);
  1174   1177         callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  1175   1178         callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  1176   1179         callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  1177   1180         sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
         1181  +      VdbeCoverage(v);
  1178   1182   #ifdef SQLITE_ENABLE_STAT3
  1179   1183         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, 
  1180   1184                                         pIdx->aiColumn[0], regSample);
  1181   1185   #else
  1182   1186         for(i=0; i<nCol; i++){
  1183   1187           i16 iCol = pIdx->aiColumn[i];
  1184   1188           sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  1185   1189         }
  1186   1190         sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
  1187   1191   #endif
  1188         -      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
         1192  +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  1189   1193         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  1190   1194         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  1191   1195         sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  1192   1196         sqlite3VdbeJumpHere(v, addrIsNull);
  1193   1197       }
  1194   1198   #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  1195   1199   
................................................................................
  1201   1205   
  1202   1206     /* Create a single sqlite_stat1 entry containing NULL as the index
  1203   1207     ** name and the row count as the content.
  1204   1208     */
  1205   1209     if( pOnlyIdx==0 && needTableCnt ){
  1206   1210       VdbeComment((v, "%s", pTab->zName));
  1207   1211       sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  1208         -    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
         1212  +    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  1209   1213       sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  1210   1214       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  1211   1215       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  1212   1216       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  1213   1217       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  1214   1218       sqlite3VdbeJumpHere(v, jZeroRows);
  1215   1219     }

Changes to src/btree.c.

  1538   1538     assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  1539   1539     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  1540   1540     assert( sqlite3_mutex_held(pBt->mutex) );
  1541   1541     if( pBt->btsFlags & BTS_SECURE_DELETE ){
  1542   1542       memset(&data[hdr], 0, pBt->usableSize - hdr);
  1543   1543     }
  1544   1544     data[hdr] = (char)flags;
  1545         -  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
         1545  +  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  1546   1546     memset(&data[hdr+1], 0, 4);
  1547   1547     data[hdr+7] = 0;
  1548   1548     put2byte(&data[hdr+5], pBt->usableSize);
  1549   1549     pPage->nFree = (u16)(pBt->usableSize - first);
  1550   1550     decodeFlags(pPage, flags);
  1551         -  pPage->hdrOffset = hdr;
  1552   1551     pPage->cellOffset = first;
  1553   1552     pPage->aDataEnd = &data[pBt->usableSize];
  1554   1553     pPage->aCellIdx = &data[first];
  1555   1554     pPage->nOverflow = 0;
  1556   1555     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  1557   1556     pPage->maskPage = (u16)(pBt->pageSize - 1);
  1558   1557     pPage->nCell = 0;
................................................................................
  3628   3627     pCur->wrFlag = (u8)wrFlag;
  3629   3628     pCur->pNext = pBt->pCursor;
  3630   3629     if( pCur->pNext ){
  3631   3630       pCur->pNext->pPrev = pCur;
  3632   3631     }
  3633   3632     pBt->pCursor = pCur;
  3634   3633     pCur->eState = CURSOR_INVALID;
  3635         -  pCur->cachedRowid = 0;
  3636   3634     return SQLITE_OK;
  3637   3635   }
  3638   3636   int sqlite3BtreeCursor(
  3639   3637     Btree *p,                                   /* The btree */
  3640   3638     int iTable,                                 /* Root page of table to open */
  3641   3639     int wrFlag,                                 /* 1 to write. 0 read-only */
  3642   3640     struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
................................................................................
  3669   3667   ** do not need to be zeroed and they are large, so we can save a lot
  3670   3668   ** of run-time by skipping the initialization of those elements.
  3671   3669   */
  3672   3670   void sqlite3BtreeCursorZero(BtCursor *p){
  3673   3671     memset(p, 0, offsetof(BtCursor, iPage));
  3674   3672   }
  3675   3673   
  3676         -/*
  3677         -** Set the cached rowid value of every cursor in the same database file
  3678         -** as pCur and having the same root page number as pCur.  The value is
  3679         -** set to iRowid.
  3680         -**
  3681         -** Only positive rowid values are considered valid for this cache.
  3682         -** The cache is initialized to zero, indicating an invalid cache.
  3683         -** A btree will work fine with zero or negative rowids.  We just cannot
  3684         -** cache zero or negative rowids, which means tables that use zero or
  3685         -** negative rowids might run a little slower.  But in practice, zero
  3686         -** or negative rowids are very uncommon so this should not be a problem.
  3687         -*/
  3688         -void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  3689         -  BtCursor *p;
  3690         -  for(p=pCur->pBt->pCursor; p; p=p->pNext){
  3691         -    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  3692         -  }
  3693         -  assert( pCur->cachedRowid==iRowid );
  3694         -}
  3695         -
  3696         -/*
  3697         -** Return the cached rowid for the given cursor.  A negative or zero
  3698         -** return value indicates that the rowid cache is invalid and should be
  3699         -** ignored.  If the rowid cache has never before been set, then a
  3700         -** zero is returned.
  3701         -*/
  3702         -sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  3703         -  return pCur->cachedRowid;
  3704         -}
  3705         -
  3706   3674   /*
  3707   3675   ** Close a cursor.  The read lock on the database file is released
  3708   3676   ** when the last cursor is closed.
  3709   3677   */
  3710   3678   int sqlite3BtreeCloseCursor(BtCursor *pCur){
  3711   3679     Btree *pBtree = pCur->pBtree;
  3712   3680     if( pBtree ){
................................................................................
  4575   4543     BtCursor *pCur,          /* The cursor to be moved */
  4576   4544     UnpackedRecord *pIdxKey, /* Unpacked index key */
  4577   4545     i64 intKey,              /* The table key */
  4578   4546     int biasRight,           /* If true, bias the search to the high end */
  4579   4547     int *pRes                /* Write search results here */
  4580   4548   ){
  4581   4549     int rc;
         4550  +  RecordCompare xRecordCompare;
  4582   4551   
  4583   4552     assert( cursorHoldsMutex(pCur) );
  4584   4553     assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  4585   4554     assert( pRes );
  4586   4555     assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  4587   4556   
  4588   4557     /* If the cursor is already positioned at the point we are trying
................................................................................
  4595   4564         return SQLITE_OK;
  4596   4565       }
  4597   4566       if( pCur->atLast && pCur->info.nKey<intKey ){
  4598   4567         *pRes = -1;
  4599   4568         return SQLITE_OK;
  4600   4569       }
  4601   4570     }
         4571  +
         4572  +  if( pIdxKey ){
         4573  +    xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
         4574  +    assert( pIdxKey->default_rc==1 
         4575  +         || pIdxKey->default_rc==0 
         4576  +         || pIdxKey->default_rc==-1
         4577  +    );
         4578  +  }else{
         4579  +    xRecordCompare = 0; /* Not actually used.  Avoids a compiler warning. */
         4580  +  }
  4602   4581   
  4603   4582     rc = moveToRoot(pCur);
  4604   4583     if( rc ){
  4605   4584       return rc;
  4606   4585     }
  4607   4586     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  4608   4587     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
................................................................................
  4680   4659           */
  4681   4660           nCell = pCell[0];
  4682   4661           if( nCell<=pPage->max1bytePayload ){
  4683   4662             /* This branch runs if the record-size field of the cell is a
  4684   4663             ** single byte varint and the record fits entirely on the main
  4685   4664             ** b-tree page.  */
  4686   4665             testcase( pCell+nCell+1==pPage->aDataEnd );
  4687         -          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
         4666  +          c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey, 0);
  4688   4667           }else if( !(pCell[1] & 0x80) 
  4689   4668             && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  4690   4669           ){
  4691   4670             /* The record-size field is a 2 byte varint and the record 
  4692   4671             ** fits entirely on the main b-tree page.  */
  4693   4672             testcase( pCell+nCell+2==pPage->aDataEnd );
  4694         -          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
         4673  +          c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey, 0);
  4695   4674           }else{
  4696   4675             /* The record flows over onto one or more overflow pages. In
  4697   4676             ** this case the whole cell needs to be parsed, a buffer allocated
  4698   4677             ** and accessPayload() used to retrieve the record into the
  4699   4678             ** buffer before VdbeRecordCompare() can be called. */
  4700   4679             void *pCellKey;
  4701   4680             u8 * const pCellBody = pCell - pPage->childPtrSize;
................................................................................
  4708   4687             }
  4709   4688             pCur->aiIdx[pCur->iPage] = (u16)idx;
  4710   4689             rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  4711   4690             if( rc ){
  4712   4691               sqlite3_free(pCellKey);
  4713   4692               goto moveto_finish;
  4714   4693             }
  4715         -          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
         4694  +          c = xRecordCompare(nCell, pCellKey, pIdxKey, 0);
  4716   4695             sqlite3_free(pCellKey);
  4717   4696           }
  4718   4697           if( c<0 ){
  4719   4698             lwr = idx+1;
  4720   4699           }else if( c>0 ){
  4721   4700             upr = idx-1;
  4722   4701           }else{
................................................................................
  6982   6961     ** that the cursor is already where it needs to be and returns without
  6983   6962     ** doing any work. To avoid thwarting these optimizations, it is important
  6984   6963     ** not to clear the cursor here.
  6985   6964     */
  6986   6965     rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  6987   6966     if( rc ) return rc;
  6988   6967   
  6989         -  /* If this is an insert into a table b-tree, invalidate any incrblob 
  6990         -  ** cursors open on the row being replaced (assuming this is a replace
  6991         -  ** operation - if it is not, the following is a no-op).  */
  6992   6968     if( pCur->pKeyInfo==0 ){
         6969  +    /* If this is an insert into a table b-tree, invalidate any incrblob 
         6970  +    ** cursors open on the row being replaced */
  6993   6971       invalidateIncrblobCursors(p, nKey, 0);
         6972  +
         6973  +    /* If the cursor is currently on the last row and we are appending a
         6974  +    ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
         6975  +    ** call */
         6976  +    if( pCur->validNKey && nKey>0 && pCur->info.nKey==nKey-1 ){
         6977  +      loc = -1;
         6978  +    }
  6994   6979     }
  6995   6980   
  6996   6981     if( !loc ){
  6997   6982       rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  6998   6983       if( rc ) return rc;
  6999   6984     }
  7000   6985     assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
................................................................................
  7056   7041     ** is advantageous to leave the cursor pointing to the last entry in
  7057   7042     ** the b-tree if possible. If the cursor is left pointing to the last
  7058   7043     ** entry in the table, and the next row inserted has an integer key
  7059   7044     ** larger than the largest existing key, it is possible to insert the
  7060   7045     ** row without seeking the cursor. This can be a big performance boost.
  7061   7046     */
  7062   7047     pCur->info.nSize = 0;
  7063         -  pCur->validNKey = 0;
  7064   7048     if( rc==SQLITE_OK && pPage->nOverflow ){
         7049  +    pCur->validNKey = 0;
  7065   7050       rc = balance(pCur);
  7066   7051   
  7067   7052       /* Must make sure nOverflow is reset to zero even if the balance()
  7068   7053       ** fails. Internal data structure corruption will result otherwise. 
  7069   7054       ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  7070   7055       ** from trying to save the current position of the cursor.  */
  7071   7056       pCur->apPage[pCur->iPage]->nOverflow = 0;

Changes to src/btree.h.

   178    178   int sqlite3BtreePrevious(BtCursor*, int *pRes);
   179    179   int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
   180    180   int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
   181    181   const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
   182    182   const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
   183    183   int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
   184    184   int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
   185         -void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
   186         -sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
   187    185   
   188    186   char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
   189    187   struct Pager *sqlite3BtreePager(Btree*);
   190    188   
   191    189   int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
   192    190   void sqlite3BtreeCacheOverflow(BtCursor *);
   193    191   void sqlite3BtreeClearCursor(BtCursor *);

Changes to src/btreeInt.h.

   496    496     BtShared *pBt;            /* The BtShared this cursor points to */
   497    497     BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
   498    498     struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
   499    499   #ifndef SQLITE_OMIT_INCRBLOB
   500    500     Pgno *aOverflow;          /* Cache of overflow page locations */
   501    501   #endif
   502    502     Pgno pgnoRoot;            /* The root page of this tree */
   503         -  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
   504    503     CellInfo info;            /* A parse of the cell we are pointing at */
   505    504     i64 nKey;        /* Size of pKey, or last integer key */
   506    505     void *pKey;      /* Saved key that was cursor's last known position */
   507    506     int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
   508    507     u8 wrFlag;                /* True if writable */
   509    508     u8 atLast;                /* Cursor pointing to the last entry */
   510    509     u8 validNKey;             /* True if info.nKey is valid */

Changes to src/build.c.

   944    944       ** set them now.
   945    945       */
   946    946       reg1 = pParse->regRowid = ++pParse->nMem;
   947    947       reg2 = pParse->regRoot = ++pParse->nMem;
   948    948       reg3 = ++pParse->nMem;
   949    949       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
   950    950       sqlite3VdbeUsesBtree(v, iDb);
   951         -    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
          951  +    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
   952    952       fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
   953    953                     1 : SQLITE_MAX_FILE_FORMAT;
   954    954       sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
   955    955       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
   956    956       sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
   957    957       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
   958    958       sqlite3VdbeJumpHere(v, j1);
................................................................................
  2671   2671     iSorter = pParse->nTab++;
  2672   2672     sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)
  2673   2673                       sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  2674   2674   
  2675   2675     /* Open the table. Loop through all rows of the table, inserting index
  2676   2676     ** records into the sorter. */
  2677   2677     sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  2678         -  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
         2678  +  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  2679   2679     regRecord = sqlite3GetTempReg(pParse);
  2680   2680   
  2681   2681     sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  2682   2682     sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  2683   2683     sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  2684         -  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
         2684  +  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  2685   2685     sqlite3VdbeJumpHere(v, addr1);
  2686   2686     if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  2687   2687     sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
  2688   2688                       (char *)pKey, P4_KEYINFO);
  2689   2689     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  2690   2690   
  2691         -  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
         2691  +  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  2692   2692     assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  2693   2693     if( pIndex->onError!=OE_None && pKey!=0 ){
  2694   2694       int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  2695   2695       sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  2696   2696       addr2 = sqlite3VdbeCurrentAddr(v);
  2697   2697       sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  2698         -                         pKey->nField - pIndex->nKeyCol);
         2698  +                         pKey->nField - pIndex->nKeyCol); VdbeCoverage(v);
  2699   2699       sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  2700   2700     }else{
  2701   2701       addr2 = sqlite3VdbeCurrentAddr(v);
  2702   2702     }
  2703   2703     sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  2704   2704     sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  2705   2705     sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  2706   2706     sqlite3ReleaseTempReg(pParse, regRecord);
  2707         -  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
         2707  +  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  2708   2708     sqlite3VdbeJumpHere(v, addr1);
  2709   2709   
  2710   2710     sqlite3VdbeAddOp1(v, OP_Close, iTab);
  2711   2711     sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  2712   2712     sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  2713   2713   }
  2714   2714   

Changes to src/delete.c.

   446    446         if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
   447    447         addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
   448    448       }else if( pPk ){
   449    449         /* Construct a composite key for the row to be deleted and remember it */
   450    450         iKey = ++pParse->nMem;
   451    451         nKey = 0;   /* Zero tells OP_Found to use a composite key */
   452    452         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
   453         -                        sqlite3IndexAffinityStr(v, pPk), P4_TRANSIENT);
          453  +                        sqlite3IndexAffinityStr(v, pPk), nPk);
   454    454         sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
   455    455       }else{
   456    456         /* Get the rowid of the row to be deleted and remember it in the RowSet */
   457    457         nKey = 1;  /* OP_Seek always uses a single rowid */
   458    458         sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
   459    459       }
   460    460     
................................................................................
   484    484       */
   485    485       if( okOnePass ){
   486    486         /* Just one row.  Hence the top-of-loop is a no-op */
   487    487         assert( nKey==nPk ); /* OP_Found will use an unpacked key */
   488    488         if( aToOpen[iDataCur-iTabCur] ){
   489    489           assert( pPk!=0 );
   490    490           sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
          491  +        VdbeCoverage(v);
   491    492         }
   492    493       }else if( pPk ){
   493         -      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur);
          494  +      addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
   494    495         sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
   495    496         assert( nKey==0 );  /* OP_Found will use a composite key */
   496    497       }else{
   497    498         addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
          499  +      VdbeCoverage(v);
   498    500         assert( nKey==1 );
   499    501       }  
   500    502     
   501    503       /* Delete the row */
   502    504   #ifndef SQLITE_OMIT_VIRTUALTABLE
   503    505       if( IsVirtual(pTab) ){
   504    506         const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
................................................................................
   514    516                                  iKey, nKey, count, OE_Default, okOnePass);
   515    517       }
   516    518     
   517    519       /* End of the loop over all rowids/primary-keys. */
   518    520       if( okOnePass ){
   519    521         sqlite3VdbeResolveLabel(v, addrBypass);
   520    522       }else if( pPk ){
   521         -      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1);
          523  +      sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
   522    524         sqlite3VdbeJumpHere(v, addrLoop);
   523    525       }else{
   524    526         sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
   525    527         sqlite3VdbeJumpHere(v, addrLoop);
   526    528       }     
   527    529     
   528    530       /* Close the cursors open on the table and its indexes. */
................................................................................
   612    614                            iDataCur, iIdxCur, iPk, (int)nPk));
   613    615   
   614    616     /* Seek cursor iCur to the row to delete. If this row no longer exists 
   615    617     ** (this can happen if a trigger program has already deleted it), do
   616    618     ** not attempt to delete it or fire any DELETE triggers.  */
   617    619     iLabel = sqlite3VdbeMakeLabel(v);
   618    620     opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
   619         -  if( !bNoSeek ) sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
          621  +  if( !bNoSeek ){
          622  +    sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
          623  +    VdbeCoverageIf(v, opSeek==OP_NotExists);
          624  +    VdbeCoverageIf(v, opSeek==OP_NotFound);
          625  +  }
   620    626    
   621    627     /* If there are any triggers to fire, allocate a range of registers to
   622    628     ** use for the old.* references in the triggers.  */
   623    629     if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
   624    630       u32 mask;                     /* Mask of OLD.* columns in use */
   625    631       int iCol;                     /* Iterator used while populating OLD.* */
   626    632       int addrStart;                /* Start of BEFORE trigger programs */
................................................................................
   654    660       /* If any BEFORE triggers were coded, then seek the cursor to the 
   655    661       ** row to be deleted again. It may be that the BEFORE triggers moved
   656    662       ** the cursor or of already deleted the row that the cursor was
   657    663       ** pointing to.
   658    664       */
   659    665       if( addrStart<sqlite3VdbeCurrentAddr(v) ){
   660    666         sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
          667  +      VdbeCoverageIf(v, opSeek==OP_NotExists);
          668  +      VdbeCoverageIf(v, opSeek==OP_NotFound);
   661    669       }
   662    670   
   663    671       /* Do FK processing. This call checks that any FK constraints that
   664    672       ** refer to this table (i.e. constraints attached to other tables) 
   665    673       ** are not violated by deleting this row.  */
   666    674       sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
   667    675     }

Changes to src/expr.c.

  1365   1365       case TK_BLOB:
  1366   1366         return 0;
  1367   1367       default:
  1368   1368         return 1;
  1369   1369     }
  1370   1370   }
  1371   1371   
  1372         -/*
  1373         -** Generate an OP_IsNull instruction that tests register iReg and jumps
  1374         -** to location iDest if the value in iReg is NULL.  The value in iReg 
  1375         -** was computed by pExpr.  If we can look at pExpr at compile-time and
  1376         -** determine that it can never generate a NULL, then the OP_IsNull operation
  1377         -** can be omitted.
  1378         -*/
  1379         -void sqlite3ExprCodeIsNullJump(
  1380         -  Vdbe *v,            /* The VDBE under construction */
  1381         -  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
  1382         -  int iReg,           /* Test the value in this register for NULL */
  1383         -  int iDest           /* Jump here if the value is null */
  1384         -){
  1385         -  if( sqlite3ExprCanBeNull(pExpr) ){
  1386         -    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  1387         -  }
  1388         -}
  1389         -
  1390   1372   /*
  1391   1373   ** Return TRUE if the given expression is a constant which would be
  1392   1374   ** unchanged by OP_Affinity with the affinity given in the second
  1393   1375   ** argument.
  1394   1376   **
  1395   1377   ** This routine is used to determine if the OP_Affinity operation
  1396   1378   ** can be omitted.  When in doubt return FALSE.  A false negative
................................................................................
  1590   1572   
  1591   1573       /* This function is only called from two places. In both cases the vdbe
  1592   1574       ** has already been allocated. So assume sqlite3GetVdbe() is always
  1593   1575       ** successful here.
  1594   1576       */
  1595   1577       assert(v);
  1596   1578       if( iCol<0 ){
  1597         -      int iAddr;
  1598         -
  1599         -      iAddr = sqlite3CodeOnce(pParse);
         1579  +      int iAddr = sqlite3CodeOnce(pParse);
         1580  +      VdbeCoverage(v);
  1600   1581   
  1601   1582         sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  1602   1583         eType = IN_INDEX_ROWID;
  1603   1584   
  1604   1585         sqlite3VdbeJumpHere(v, iAddr);
  1605   1586       }else{
  1606   1587         Index *pIdx;                         /* Iterator variable */
................................................................................
  1617   1598         int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  1618   1599   
  1619   1600         for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  1620   1601           if( (pIdx->aiColumn[0]==iCol)
  1621   1602            && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  1622   1603            && (!mustBeUnique || (pIdx->nKeyCol==1 && pIdx->onError!=OE_None))
  1623   1604           ){
  1624         -          int iAddr = sqlite3CodeOnce(pParse);
         1605  +          int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  1625   1606             sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  1626   1607             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  1627   1608             VdbeComment((v, "%s", pIdx->zName));
  1628   1609             assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  1629   1610             eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  1630   1611   
  1631         -          sqlite3VdbeJumpHere(v, iAddr);
  1632   1612             if( prNotFound && !pTab->aCol[iCol].notNull ){
  1633   1613               *prNotFound = ++pParse->nMem;
  1634   1614               sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  1635   1615             }
         1616  +          sqlite3VdbeJumpHere(v, iAddr);
  1636   1617           }
  1637   1618         }
  1638   1619       }
  1639   1620     }
  1640   1621   
  1641   1622     if( eType==0 ){
  1642   1623       /* Could not found an existing table or index to use as the RHS b-tree.
................................................................................
  1717   1698     **    *  The right-hand side is an expression list containing variables
  1718   1699     **    *  We are inside a trigger
  1719   1700     **
  1720   1701     ** If all of the above are false, then we can run this code just once
  1721   1702     ** save the results, and reuse the same result on subsequent invocations.
  1722   1703     */
  1723   1704     if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  1724         -    testAddr = sqlite3CodeOnce(pParse);
         1705  +    testAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  1725   1706     }
  1726   1707   
  1727   1708   #ifndef SQLITE_OMIT_EXPLAIN
  1728   1709     if( pParse->explain==2 ){
  1729   1710       char *zMsg = sqlite3MPrintf(
  1730   1711           pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  1731   1712           pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
................................................................................
  1833   1814             if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  1834   1815               sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  1835   1816             }else{
  1836   1817               r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  1837   1818               if( isRowid ){
  1838   1819                 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  1839   1820                                   sqlite3VdbeCurrentAddr(v)+2);
         1821  +              VdbeCoverage(v);
  1840   1822                 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  1841   1823               }else{
  1842   1824                 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  1843   1825                 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  1844   1826                 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  1845   1827               }
  1846   1828             }
................................................................................
  1956   1938   
  1957   1939     /* If the LHS is NULL, then the result is either false or NULL depending
  1958   1940     ** on whether the RHS is empty or not, respectively.
  1959   1941     */
  1960   1942     if( destIfNull==destIfFalse ){
  1961   1943       /* Shortcut for the common case where the false and NULL outcomes are
  1962   1944       ** the same. */
  1963         -    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
         1945  +    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  1964   1946     }else{
  1965         -    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
         1947  +    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  1966   1948       sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
         1949  +    VdbeCoverage(v);
  1967   1950       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  1968   1951       sqlite3VdbeJumpHere(v, addr1);
  1969   1952     }
  1970   1953   
  1971   1954     if( eType==IN_INDEX_ROWID ){
  1972   1955       /* In this case, the RHS is the ROWID of table b-tree
  1973   1956       */
  1974         -    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
         1957  +    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  1975   1958       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
         1959  +    VdbeCoverage(v);
  1976   1960     }else{
  1977   1961       /* In this case, the RHS is an index b-tree.
  1978   1962       */
  1979   1963       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  1980   1964   
  1981   1965       /* If the set membership test fails, then the result of the 
  1982   1966       ** "x IN (...)" expression must be either 0 or NULL. If the set
................................................................................
  1989   1973         ** cannot contain NULL values. This happens as the result
  1990   1974         ** of a "NOT NULL" constraint in the database schema.
  1991   1975         **
  1992   1976         ** Also run this branch if NULL is equivalent to FALSE
  1993   1977         ** for this particular IN operator.
  1994   1978         */
  1995   1979         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  1996         -
         1980  +      VdbeCoverage(v);
  1997   1981       }else{
  1998   1982         /* In this branch, the RHS of the IN might contain a NULL and
  1999   1983         ** the presence of a NULL on the RHS makes a difference in the
  2000   1984         ** outcome.
  2001   1985         */
  2002         -      int j1, j2, j3;
         1986  +      int j1, j2;
  2003   1987   
  2004   1988         /* First check to see if the LHS is contained in the RHS.  If so,
  2005   1989         ** then the presence of NULLs in the RHS does not matter, so jump
  2006   1990         ** over all of the code that follows.
  2007   1991         */
  2008   1992         j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
         1993  +      VdbeCoverage(v);
  2009   1994   
  2010   1995         /* Here we begin generating code that runs if the LHS is not
  2011   1996         ** contained within the RHS.  Generate additional code that
  2012   1997         ** tests the RHS for NULLs.  If the RHS contains a NULL then
  2013   1998         ** jump to destIfNull.  If there are no NULLs in the RHS then
  2014   1999         ** jump to destIfFalse.
  2015   2000         */
  2016         -      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  2017         -      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  2018         -      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  2019         -      sqlite3VdbeJumpHere(v, j3);
  2020         -      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
         2001  +      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull); VdbeCoverage(v);
         2002  +      sqlite3VdbeAddOp2(v, OP_IfNot, rRhsHasNull, destIfFalse); VdbeCoverage(v);
         2003  +      j2 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
         2004  +      VdbeCoverage(v);
         2005  +      sqlite3VdbeAddOp2(v, OP_Integer, 0, rRhsHasNull);
         2006  +      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  2021   2007         sqlite3VdbeJumpHere(v, j2);
  2022         -
  2023         -      /* Jump to the appropriate target depending on whether or not
  2024         -      ** the RHS contains a NULL
  2025         -      */
  2026         -      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  2027         -      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
         2008  +      sqlite3VdbeAddOp2(v, OP_Integer, 1, rRhsHasNull);
         2009  +      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  2028   2010   
  2029   2011         /* The OP_Found at the top of this branch jumps here when true, 
  2030   2012         ** causing the overall IN expression evaluation to fall through.
  2031   2013         */
  2032   2014         sqlite3VdbeJumpHere(v, j1);
  2033   2015       }
  2034   2016     }
................................................................................
  2541   2523   #endif /* SQLITE_OMIT_CAST */
  2542   2524       case TK_LT:
  2543   2525       case TK_LE:
  2544   2526       case TK_GT:
  2545   2527       case TK_GE:
  2546   2528       case TK_NE:
  2547   2529       case TK_EQ: {
  2548         -      assert( TK_LT==OP_Lt );
  2549         -      assert( TK_LE==OP_Le );
  2550         -      assert( TK_GT==OP_Gt );
  2551         -      assert( TK_GE==OP_Ge );
  2552         -      assert( TK_EQ==OP_Eq );
  2553         -      assert( TK_NE==OP_Ne );
  2554         -      testcase( op==TK_LT );
  2555         -      testcase( op==TK_LE );
  2556         -      testcase( op==TK_GT );
  2557         -      testcase( op==TK_GE );
  2558         -      testcase( op==TK_EQ );
  2559         -      testcase( op==TK_NE );
  2560   2530         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2561   2531         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  2562   2532         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  2563   2533                     r1, r2, inReg, SQLITE_STOREP2);
         2534  +      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
         2535  +      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
         2536  +      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
         2537  +      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
         2538  +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
         2539  +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  2564   2540         testcase( regFree1==0 );
  2565   2541         testcase( regFree2==0 );
  2566   2542         break;
  2567   2543       }
  2568   2544       case TK_IS:
  2569   2545       case TK_ISNOT: {
  2570   2546         testcase( op==TK_IS );
  2571   2547         testcase( op==TK_ISNOT );
  2572   2548         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2573   2549         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  2574   2550         op = (op==TK_IS) ? TK_EQ : TK_NE;
  2575   2551         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  2576   2552                     r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
         2553  +      VdbeCoverageIf(v, op==TK_EQ);
         2554  +      VdbeCoverageIf(v, op==TK_NE);
  2577   2555         testcase( regFree1==0 );
  2578   2556         testcase( regFree2==0 );
  2579   2557         break;
  2580   2558       }
  2581   2559       case TK_AND:
  2582   2560       case TK_OR:
  2583   2561       case TK_PLUS:
................................................................................
  2586   2564       case TK_REM:
  2587   2565       case TK_BITAND:
  2588   2566       case TK_BITOR:
  2589   2567       case TK_SLASH:
  2590   2568       case TK_LSHIFT:
  2591   2569       case TK_RSHIFT: 
  2592   2570       case TK_CONCAT: {
  2593         -      assert( TK_AND==OP_And );
  2594         -      assert( TK_OR==OP_Or );
  2595         -      assert( TK_PLUS==OP_Add );
  2596         -      assert( TK_MINUS==OP_Subtract );
  2597         -      assert( TK_REM==OP_Remainder );
  2598         -      assert( TK_BITAND==OP_BitAnd );
  2599         -      assert( TK_BITOR==OP_BitOr );
  2600         -      assert( TK_SLASH==OP_Divide );
  2601         -      assert( TK_LSHIFT==OP_ShiftLeft );
  2602         -      assert( TK_RSHIFT==OP_ShiftRight );
  2603         -      assert( TK_CONCAT==OP_Concat );
  2604         -      testcase( op==TK_AND );
  2605         -      testcase( op==TK_OR );
  2606         -      testcase( op==TK_PLUS );
  2607         -      testcase( op==TK_MINUS );
  2608         -      testcase( op==TK_REM );
  2609         -      testcase( op==TK_BITAND );
  2610         -      testcase( op==TK_BITOR );
  2611         -      testcase( op==TK_SLASH );
  2612         -      testcase( op==TK_LSHIFT );
  2613         -      testcase( op==TK_RSHIFT );
  2614         -      testcase( op==TK_CONCAT );
         2571  +      assert( TK_AND==OP_And );            testcase( op==TK_AND );
         2572  +      assert( TK_OR==OP_Or );              testcase( op==TK_OR );
         2573  +      assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
         2574  +      assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
         2575  +      assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
         2576  +      assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
         2577  +      assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
         2578  +      assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
         2579  +      assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
         2580  +      assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
         2581  +      assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
  2615   2582         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2616   2583         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  2617   2584         sqlite3VdbeAddOp3(v, op, r2, r1, target);
  2618   2585         testcase( regFree1==0 );
  2619   2586         testcase( regFree2==0 );
  2620   2587         break;
  2621   2588       }
................................................................................
  2639   2606           testcase( regFree2==0 );
  2640   2607         }
  2641   2608         inReg = target;
  2642   2609         break;
  2643   2610       }
  2644   2611       case TK_BITNOT:
  2645   2612       case TK_NOT: {
  2646         -      assert( TK_BITNOT==OP_BitNot );
  2647         -      assert( TK_NOT==OP_Not );
  2648         -      testcase( op==TK_BITNOT );
  2649         -      testcase( op==TK_NOT );
         2613  +      assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
         2614  +      assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
  2650   2615         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2651   2616         testcase( regFree1==0 );
  2652   2617         inReg = target;
  2653   2618         sqlite3VdbeAddOp2(v, op, r1, inReg);
  2654   2619         break;
  2655   2620       }
  2656   2621       case TK_ISNULL:
  2657   2622       case TK_NOTNULL: {
  2658   2623         int addr;
  2659         -      assert( TK_ISNULL==OP_IsNull );
  2660         -      assert( TK_NOTNULL==OP_NotNull );
  2661         -      testcase( op==TK_ISNULL );
  2662         -      testcase( op==TK_NOTNULL );
         2624  +      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
         2625  +      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  2663   2626         sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  2664   2627         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  2665   2628         testcase( regFree1==0 );
  2666   2629         addr = sqlite3VdbeAddOp1(v, op, r1);
         2630  +      VdbeCoverageIf(v, op==TK_ISNULL);
         2631  +      VdbeCoverageIf(v, op==TK_NOTNULL);
  2667   2632         sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  2668   2633         sqlite3VdbeJumpHere(v, addr);
  2669   2634         break;
  2670   2635       }
  2671   2636       case TK_AGG_FUNCTION: {
  2672   2637         AggInfo *pInfo = pExpr->pAggInfo;
  2673   2638         if( pInfo==0 ){
................................................................................
  2711   2676         */
  2712   2677         if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  2713   2678           int endCoalesce = sqlite3VdbeMakeLabel(v);
  2714   2679           assert( nFarg>=2 );
  2715   2680           sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  2716   2681           for(i=1; i<nFarg; i++){
  2717   2682             sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
         2683  +          VdbeCoverage(v);
  2718   2684             sqlite3ExprCacheRemove(pParse, target, 1);
  2719   2685             sqlite3ExprCachePush(pParse);
  2720   2686             sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  2721   2687             sqlite3ExprCachePop(pParse, 1);
  2722   2688           }
  2723   2689           sqlite3VdbeResolveLabel(v, endCoalesce);
  2724   2690           break;
................................................................................
  2848   2814         r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  2849   2815         r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  2850   2816         testcase( regFree1==0 );
  2851   2817         testcase( regFree2==0 );
  2852   2818         r3 = sqlite3GetTempReg(pParse);
  2853   2819         r4 = sqlite3GetTempReg(pParse);
  2854   2820         codeCompare(pParse, pLeft, pRight, OP_Ge,
  2855         -                  r1, r2, r3, SQLITE_STOREP2);
         2821  +                  r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
  2856   2822         pLItem++;
  2857   2823         pRight = pLItem->pExpr;
  2858   2824         sqlite3ReleaseTempReg(pParse, regFree2);
  2859   2825         r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  2860   2826         testcase( regFree2==0 );
  2861   2827         codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
         2828  +      VdbeCoverage(v);
  2862   2829         sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  2863   2830         sqlite3ReleaseTempReg(pParse, r3);
  2864   2831         sqlite3ReleaseTempReg(pParse, r4);
  2865   2832         break;
  2866   2833       }
  2867   2834       case TK_COLLATE: 
  2868   2835       case TK_UPLUS: {
................................................................................
  3021   2988         if( pExpr->affinity==OE_Abort ){
  3022   2989           sqlite3MayAbort(pParse);
  3023   2990         }
  3024   2991         assert( !ExprHasProperty(pExpr, EP_IntValue) );
  3025   2992         if( pExpr->affinity==OE_Ignore ){
  3026   2993           sqlite3VdbeAddOp4(
  3027   2994               v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
         2995  +        VdbeCoverage(v);
  3028   2996         }else{
  3029   2997           sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  3030   2998                                 pExpr->affinity, pExpr->u.zToken, 0, 0);
  3031   2999         }
  3032   3000   
  3033   3001         break;
  3034   3002       }
................................................................................
  3108   3076   }
  3109   3077   
  3110   3078   /*
  3111   3079   ** Generate code that will evaluate expression pExpr and store the
  3112   3080   ** results in register target.  The results are guaranteed to appear
  3113   3081   ** in register target.
  3114   3082   */
  3115         -int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
         3083  +void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  3116   3084     int inReg;
  3117   3085   
  3118   3086     assert( target>0 && target<=pParse->nMem );
  3119   3087     if( pExpr && pExpr->op==TK_REGISTER ){
  3120   3088       sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  3121   3089     }else{
  3122   3090       inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  3123   3091       assert( pParse->pVdbe || pParse->db->mallocFailed );
  3124   3092       if( inReg!=target && pParse->pVdbe ){
  3125   3093         sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  3126   3094       }
  3127   3095     }
  3128         -  return target;
         3096  +}
         3097  +
         3098  +/*
         3099  +** Generate code that will evaluate expression pExpr and store the
         3100  +** results in register target.  The results are guaranteed to appear
         3101  +** in register target.  If the expression is constant, then this routine
         3102  +** might choose to code the expression at initialization time.
         3103  +*/
         3104  +void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
         3105  +  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
         3106  +    sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
         3107  +  }else{
         3108  +    sqlite3ExprCode(pParse, pExpr, target);
         3109  +  }
  3129   3110   }
  3130   3111   
  3131   3112   /*
  3132   3113   ** Generate code that evalutes the given expression and puts the result
  3133   3114   ** in register target.
  3134   3115   **
  3135   3116   ** Also make a copy of the expression results into another "cache" register
................................................................................
  3136   3117   ** and modify the expression so that the next time it is evaluated,
  3137   3118   ** the result is a copy of the cache register.
  3138   3119   **
  3139   3120   ** This routine is used for expressions that are used multiple 
  3140   3121   ** times.  They are evaluated once and the results of the expression
  3141   3122   ** are reused.
  3142   3123   */
  3143         -int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
         3124  +void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  3144   3125     Vdbe *v = pParse->pVdbe;
  3145         -  int inReg;
  3146         -  inReg = sqlite3ExprCode(pParse, pExpr, target);
         3126  +  int iMem;
         3127  +
  3147   3128     assert( target>0 );
  3148         -  /* The only place, other than this routine, where expressions can be
  3149         -  ** converted to TK_REGISTER is internal subexpressions in BETWEEN and
  3150         -  ** CASE operators.  Neither ever calls this routine.  And this routine
  3151         -  ** is never called twice on the same expression.  Hence it is impossible
  3152         -  ** for the input to this routine to already be a register.  Nevertheless,
  3153         -  ** it seems prudent to keep the ALWAYS() in case the conditions above
  3154         -  ** change with future modifications or enhancements. */
  3155         -  if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
  3156         -    int iMem;
  3157         -    iMem = ++pParse->nMem;
  3158         -    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  3159         -    exprToRegister(pExpr, iMem);
  3160         -  }
  3161         -  return inReg;
         3129  +  assert( pExpr->op!=TK_REGISTER );
         3130  +  sqlite3ExprCode(pParse, pExpr, target);
         3131  +  iMem = ++pParse->nMem;
         3132  +  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
         3133  +  exprToRegister(pExpr, iMem);
  3162   3134   }
  3163   3135   
  3164   3136   #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  3165   3137   /*
  3166   3138   ** Generate a human-readable explanation of an expression tree.
  3167   3139   */
  3168   3140   void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
................................................................................
  3589   3561       }
  3590   3562       case TK_LT:
  3591   3563       case TK_LE:
  3592   3564       case TK_GT:
  3593   3565       case TK_GE:
  3594   3566       case TK_NE:
  3595   3567       case TK_EQ: {
  3596         -      assert( TK_LT==OP_Lt );
  3597         -      assert( TK_LE==OP_Le );
  3598         -      assert( TK_GT==OP_Gt );
  3599         -      assert( TK_GE==OP_Ge );
  3600         -      assert( TK_EQ==OP_Eq );
  3601         -      assert( TK_NE==OP_Ne );
  3602         -      testcase( op==TK_LT );
  3603         -      testcase( op==TK_LE );
  3604         -      testcase( op==TK_GT );
  3605         -      testcase( op==TK_GE );
  3606         -      testcase( op==TK_EQ );
  3607         -      testcase( op==TK_NE );
  3608   3568         testcase( jumpIfNull==0 );
  3609   3569         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3610   3570         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3611   3571         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3612   3572                     r1, r2, dest, jumpIfNull);
         3573  +      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
         3574  +      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
         3575  +      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
         3576  +      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
         3577  +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
         3578  +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  3613   3579         testcase( regFree1==0 );
  3614   3580         testcase( regFree2==0 );
  3615   3581         break;
  3616   3582       }
  3617   3583       case TK_IS:
  3618   3584       case TK_ISNOT: {
  3619   3585         testcase( op==TK_IS );
  3620   3586         testcase( op==TK_ISNOT );
  3621   3587         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3622   3588         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3623   3589         op = (op==TK_IS) ? TK_EQ : TK_NE;
  3624   3590         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3625   3591                     r1, r2, dest, SQLITE_NULLEQ);
         3592  +      VdbeCoverageIf(v, op==TK_EQ);
         3593  +      VdbeCoverageIf(v, op==TK_NE);
  3626   3594         testcase( regFree1==0 );
  3627   3595         testcase( regFree2==0 );
  3628   3596         break;
  3629   3597       }
  3630   3598       case TK_ISNULL:
  3631   3599       case TK_NOTNULL: {
  3632         -      assert( TK_ISNULL==OP_IsNull );
  3633         -      assert( TK_NOTNULL==OP_NotNull );
  3634         -      testcase( op==TK_ISNULL );
  3635         -      testcase( op==TK_NOTNULL );
         3600  +      assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
         3601  +      assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  3636   3602         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3637   3603         sqlite3VdbeAddOp2(v, op, r1, dest);
         3604  +      VdbeCoverageIf(v, op==TK_ISNULL);
         3605  +      VdbeCoverageIf(v, op==TK_NOTNULL);
  3638   3606         testcase( regFree1==0 );
  3639   3607         break;
  3640   3608       }
  3641   3609       case TK_BETWEEN: {
  3642   3610         testcase( jumpIfNull==0 );
  3643   3611         exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  3644   3612         break;
................................................................................
  3657   3625         if( exprAlwaysTrue(pExpr) ){
  3658   3626           sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  3659   3627         }else if( exprAlwaysFalse(pExpr) ){
  3660   3628           /* No-op */
  3661   3629         }else{
  3662   3630           r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  3663   3631           sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
         3632  +        VdbeCoverage(v);
  3664   3633           testcase( regFree1==0 );
  3665   3634           testcase( jumpIfNull==0 );
  3666   3635         }
  3667   3636         break;
  3668   3637       }
  3669   3638     }
  3670   3639     sqlite3ReleaseTempReg(pParse, regFree1);
................................................................................
  3748   3717       }
  3749   3718       case TK_LT:
  3750   3719       case TK_LE:
  3751   3720       case TK_GT:
  3752   3721       case TK_GE:
  3753   3722       case TK_NE:
  3754   3723       case TK_EQ: {
  3755         -      testcase( op==TK_LT );
  3756         -      testcase( op==TK_LE );
  3757         -      testcase( op==TK_GT );
  3758         -      testcase( op==TK_GE );
  3759         -      testcase( op==TK_EQ );
  3760         -      testcase( op==TK_NE );
  3761   3724         testcase( jumpIfNull==0 );
  3762   3725         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3763   3726         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3764   3727         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3765   3728                     r1, r2, dest, jumpIfNull);
         3729  +      assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
         3730  +      assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
         3731  +      assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
         3732  +      assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
         3733  +      assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
         3734  +      assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  3766   3735         testcase( regFree1==0 );
  3767   3736         testcase( regFree2==0 );
  3768   3737         break;
  3769   3738       }
  3770   3739       case TK_IS:
  3771   3740       case TK_ISNOT: {
  3772   3741         testcase( pExpr->op==TK_IS );
  3773   3742         testcase( pExpr->op==TK_ISNOT );
  3774   3743         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3775   3744         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  3776   3745         op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  3777   3746         codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  3778   3747                     r1, r2, dest, SQLITE_NULLEQ);
         3748  +      VdbeCoverageIf(v, op==TK_EQ);
         3749  +      VdbeCoverageIf(v, op==TK_NE);
  3779   3750         testcase( regFree1==0 );
  3780   3751         testcase( regFree2==0 );
  3781   3752         break;
  3782   3753       }
  3783   3754       case TK_ISNULL:
  3784   3755       case TK_NOTNULL: {
  3785         -      testcase( op==TK_ISNULL );
  3786         -      testcase( op==TK_NOTNULL );
  3787   3756         r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  3788   3757         sqlite3VdbeAddOp2(v, op, r1, dest);
         3758  +      testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
         3759  +      testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
  3789   3760         testcase( regFree1==0 );
  3790   3761         break;
  3791   3762       }
  3792   3763       case TK_BETWEEN: {
  3793   3764         testcase( jumpIfNull==0 );
  3794   3765         exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  3795   3766         break;
................................................................................
  3810   3781         if( exprAlwaysFalse(pExpr) ){
  3811   3782           sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  3812   3783         }else if( exprAlwaysTrue(pExpr) ){
  3813   3784           /* no-op */
  3814   3785         }else{
  3815   3786           r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  3816   3787           sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
         3788  +        VdbeCoverage(v);
  3817   3789           testcase( regFree1==0 );
  3818   3790           testcase( jumpIfNull==0 );
  3819   3791         }
  3820   3792         break;
  3821   3793       }
  3822   3794     }
  3823   3795     sqlite3ReleaseTempReg(pParse, regFree1);

Changes to src/fkey.c.

   336    336     ** to check if deleting this row resolves any outstanding violations.
   337    337     **
   338    338     ** Check if any of the key columns in the child table row are NULL. If 
   339    339     ** any are, then the constraint is considered satisfied. No need to 
   340    340     ** search for a matching row in the parent table.  */
   341    341     if( nIncr<0 ){
   342    342       sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
          343  +    VdbeCoverage(v);
   343    344     }
   344    345     for(i=0; i<pFKey->nCol; i++){
   345    346       int iReg = aiCol[i] + regData + 1;
   346         -    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
          347  +    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
   347    348     }
   348    349   
   349    350     if( isIgnore==0 ){
   350    351       if( pIdx==0 ){
   351    352         /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
   352    353         ** column of the parent table (table pTab).  */
   353    354         int iMustBeInt;               /* Address of MustBeInt instruction */
................................................................................
   356    357         /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
   357    358         ** apply the affinity of the parent key). If this fails, then there
   358    359         ** is no matching parent key. Before using MustBeInt, make a copy of
   359    360         ** the value. Otherwise, the value inserted into the child key column
   360    361         ** will have INTEGER affinity applied to it, which may not be correct.  */
   361    362         sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
   362    363         iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
          364  +      VdbeCoverage(v);
   363    365     
   364    366         /* If the parent table is the same as the child table, and we are about
   365    367         ** to increment the constraint-counter (i.e. this is an INSERT operation),
   366    368         ** then check if the row being inserted matches itself. If so, do not
   367    369         ** increment the constraint-counter.  */
   368    370         if( pTab==pFKey->pFrom && nIncr==1 ){
   369         -        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
          371  +        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
          372  +        sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
   370    373         }
   371    374     
   372    375         sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
   373         -      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
          376  +      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
   374    377         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   375    378         sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
   376    379         sqlite3VdbeJumpHere(v, iMustBeInt);
   377    380         sqlite3ReleaseTempReg(pParse, regTemp);
   378    381       }else{
   379    382         int nCol = pFKey->nCol;
   380    383         int regTemp = sqlite3GetTempRange(pParse, nCol);
................................................................................
   402    405             int iChild = aiCol[i]+1+regData;
   403    406             int iParent = pIdx->aiColumn[i]+1+regData;
   404    407             assert( aiCol[i]!=pTab->iPKey );
   405    408             if( pIdx->aiColumn[i]==pTab->iPKey ){
   406    409               /* The parent key is a composite key that includes the IPK column */
   407    410               iParent = regData;
   408    411             }
   409         -          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
          412  +          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
   410    413             sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   411    414           }
   412    415           sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
   413    416         }
   414    417     
   415         -      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
   416         -      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
   417         -      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
          418  +      sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
          419  +                        sqlite3IndexAffinityStr(v,pIdx), nCol);
          420  +      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
   418    421     
   419    422         sqlite3ReleaseTempReg(pParse, regRec);
   420    423         sqlite3ReleaseTempRange(pParse, regTemp, nCol);
   421    424       }
   422    425     }
   423    426   
   424    427     if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
................................................................................
   548    551     assert( pIdx==0 || pIdx->pTable==pTab );
   549    552     assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
   550    553     assert( pIdx!=0 || pFKey->nCol==1 );
   551    554     assert( pIdx!=0 || HasRowid(pTab) );
   552    555   
   553    556     if( nIncr<0 ){
   554    557       iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
          558  +    VdbeCoverage(v);
   555    559     }
   556    560   
   557    561     /* Create an Expr object representing an SQL expression like:
   558    562     **
   559    563     **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
   560    564     **
   561    565     ** The collation sequence used for the comparison should be that of
................................................................................
   710    714         ** when this statement is run.  */
   711    715         FKey *p;
   712    716         for(p=pTab->pFKey; p; p=p->pNextFrom){
   713    717           if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
   714    718         }
   715    719         if( !p ) return;
   716    720         iSkip = sqlite3VdbeMakeLabel(v);
   717         -      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
          721  +      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
   718    722       }
   719    723   
   720    724       pParse->disableTriggers = 1;
   721    725       sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
   722    726       pParse->disableTriggers = 0;
   723    727   
   724    728       /* If the DELETE has generated immediate foreign key constraint 
................................................................................
   728    732       **
   729    733       ** If the SQLITE_DeferFKs flag is set, then this is not required, as
   730    734       ** the statement transaction will not be rolled back even if FK
   731    735       ** constraints are violated.
   732    736       */
   733    737       if( (db->flags & SQLITE_DeferFKs)==0 ){
   734    738         sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
          739  +      VdbeCoverage(v);
   735    740         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
   736    741             OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
   737    742       }
   738    743   
   739    744       if( iSkip ){
   740    745         sqlite3VdbeResolveLabel(v, iSkip);
   741    746       }
................................................................................
   887    892           ** missing, behave as if it is empty. i.e. decrement the relevant
   888    893           ** FK counter for each row of the current table with non-NULL keys.
   889    894           */
   890    895           Vdbe *v = sqlite3GetVdbe(pParse);
   891    896           int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
   892    897           for(i=0; i<pFKey->nCol; i++){
   893    898             int iReg = pFKey->aCol[i].iFrom + regOld + 1;
   894         -          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
          899  +          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
   895    900           }
   896    901           sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
   897    902         }
   898    903         continue;
   899    904       }
   900    905       assert( pFKey->nCol==1 || (aiFree && pIdx) );
   901    906   

Changes to src/insert.c.

    94     94       pIdx->zColAff[n] = 0;
    95     95     }
    96     96    
    97     97     return pIdx->zColAff;
    98     98   }
    99     99   
   100    100   /*
   101         -** Set P4 of the most recently inserted opcode to a column affinity
   102         -** string for table pTab. A column affinity string has one character
   103         -** for each column indexed by the index, according to the affinity of the
   104         -** column:
          101  +** Compute the affinity string for table pTab, if it has not already been
          102  +** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
          103  +**
          104  +** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values and
          105  +** if iReg>0 then code an OP_Affinity opcode that will set the affinities
          106  +** for register iReg and following.  Or if affinities exists and iReg==0,
          107  +** then just set the P4 operand of the previous opcode (which should  be
          108  +** an OP_MakeRecord) to the affinity string.
          109  +**
          110  +** A column affinity string has one character column:
   105    111   **
   106    112   **  Character      Column affinity
   107    113   **  ------------------------------
   108    114   **  'a'            TEXT
   109    115   **  'b'            NONE
   110    116   **  'c'            NUMERIC
   111    117   **  'd'            INTEGER
   112    118   **  'e'            REAL
   113    119   */
   114         -void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
   115         -  /* The first time a column affinity string for a particular table
   116         -  ** is required, it is allocated and populated here. It is then 
   117         -  ** stored as a member of the Table structure for subsequent use.
   118         -  **
   119         -  ** The column affinity string will eventually be deleted by
   120         -  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
   121         -  */
   122         -  if( !pTab->zColAff ){
   123         -    char *zColAff;
   124         -    int i;
          120  +void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
          121  +  int i;
          122  +  char *zColAff = pTab->zColAff;
          123  +  if( zColAff==0 ){
   125    124       sqlite3 *db = sqlite3VdbeDb(v);
   126         -
   127    125       zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
   128    126       if( !zColAff ){
   129    127         db->mallocFailed = 1;
   130    128         return;
   131    129       }
   132    130   
   133    131       for(i=0; i<pTab->nCol; i++){
   134    132         zColAff[i] = pTab->aCol[i].affinity;
   135    133       }
   136         -    zColAff[pTab->nCol] = '\0';
   137         -
          134  +    do{
          135  +      zColAff[i--] = 0;
          136  +    }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
   138    137       pTab->zColAff = zColAff;
   139    138     }
   140         -
   141         -  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
          139  +  i = sqlite3Strlen30(zColAff);
          140  +  if( i ){
          141  +    if( iReg ){
          142  +      sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
          143  +    }else{
          144  +      sqlite3VdbeChangeP4(v, -1, zColAff, i);
          145  +    }
          146  +  }
   142    147   }
   143    148   
   144    149   /*
   145    150   ** Return non-zero if the table pTab in database iDb or any of its indices
   146    151   ** have been opened at any point in the VDBE program beginning at location
   147    152   ** iStartAddr throught the end of the program.  This is used to see if 
   148    153   ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
   149    154   ** run without using temporary table for the results of the SELECT. 
   150    155   */
   151         -static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
          156  +static int readsTable(Parse *p, int iDb, Table *pTab){
   152    157     Vdbe *v = sqlite3GetVdbe(p);
   153    158     int i;
   154    159     int iEnd = sqlite3VdbeCurrentAddr(v);
   155    160   #ifndef SQLITE_OMIT_VIRTUALTABLE
   156    161     VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
   157    162   #endif
   158    163   
   159         -  for(i=iStartAddr; i<iEnd; i++){
          164  +  for(i=1; i<iEnd; i++){
   160    165       VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
   161    166       assert( pOp!=0 );
   162    167       if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
   163    168         Index *pIndex;
   164    169         int tnum = pOp->p2;
   165    170         if( tnum==pTab->tnum ){
   166    171           return 1;
................................................................................
   253    258       pDb = &db->aDb[p->iDb];
   254    259       memId = p->regCtr;
   255    260       assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   256    261       sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
   257    262       sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
   258    263       addr = sqlite3VdbeCurrentAddr(v);
   259    264       sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
   260         -    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
          265  +    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
   261    266       sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
   262         -    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
          267  +    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
   263    268       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
   264    269       sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   265    270       sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
   266    271       sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
   267         -    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
          272  +    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
   268    273       sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
   269    274       sqlite3VdbeAddOp0(v, OP_Close);
   270    275     }
   271    276   }
   272    277   
   273    278   /*
   274    279   ** Update the maximum rowid for an autoincrement calculation.
................................................................................
   295    300     AutoincInfo *p;
   296    301     Vdbe *v = pParse->pVdbe;
   297    302     sqlite3 *db = pParse->db;
   298    303   
   299    304     assert( v );
   300    305     for(p = pParse->pAinc; p; p = p->pNext){
   301    306       Db *pDb = &db->aDb[p->iDb];
   302         -    int j1, j2, j3, j4, j5;
          307  +    int j1;
   303    308       int iRec;
   304    309       int memId = p->regCtr;
   305    310   
   306    311       iRec = sqlite3GetTempReg(pParse);
   307    312       assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
   308    313       sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
   309         -    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
   310         -    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
   311         -    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
   312         -    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
   313         -    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
   314         -    sqlite3VdbeJumpHere(v, j2);
          314  +    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
   315    315       sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
   316         -    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
   317         -    sqlite3VdbeJumpHere(v, j4);
   318         -    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
   319    316       sqlite3VdbeJumpHere(v, j1);
   320         -    sqlite3VdbeJumpHere(v, j5);
   321    317       sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
   322    318       sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
   323    319       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   324    320       sqlite3VdbeAddOp0(v, OP_Close);
   325    321       sqlite3ReleaseTempReg(pParse, iRec);
   326    322     }
   327    323   }
................................................................................
   329    325   /*
   330    326   ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
   331    327   ** above are all no-ops
   332    328   */
   333    329   # define autoIncBegin(A,B,C) (0)
   334    330   # define autoIncStep(A,B,C)
   335    331   #endif /* SQLITE_OMIT_AUTOINCREMENT */
   336         -
   337         -
   338         -/*
   339         -** Generate code for a co-routine that will evaluate a subquery one
   340         -** row at a time.
   341         -**
   342         -** The pSelect parameter is the subquery that the co-routine will evaluation.
   343         -** Information about the location of co-routine and the registers it will use
   344         -** is returned by filling in the pDest object.
   345         -**
   346         -** Registers are allocated as follows:
   347         -**
   348         -**   pDest->iSDParm      The register holding the next entry-point of the
   349         -**                       co-routine.  Run the co-routine to its next breakpoint
   350         -**                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
   351         -**
   352         -**   pDest->iSdst        First result register.
   353         -**
   354         -**   pDest->nSdst        Number of result registers.
   355         -**
   356         -** At EOF the first result register will be marked as "undefined" so that
   357         -** the caller can know when to stop reading results.
   358         -**
   359         -** This routine handles all of the register allocation and fills in the
   360         -** pDest structure appropriately.
   361         -**
   362         -** Here is a schematic of the generated code assuming that X is the 
   363         -** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
   364         -** completed flag reg[pDest->iSDParm+1], and R and S are the range of
   365         -** registers that hold the result set, reg[pDest->iSdst] through
   366         -** reg[pDest->iSdst+pDest->nSdst-1]:
   367         -**
   368         -**         X <- A
   369         -**         goto B
   370         -**      A: setup for the SELECT
   371         -**         loop rows in the SELECT
   372         -**           load results into registers R..S
   373         -**           yield X
   374         -**         end loop
   375         -**         cleanup after the SELECT
   376         -**         end co-routine R
   377         -**      B:
   378         -**
   379         -** To use this subroutine, the caller generates code as follows:
   380         -**
   381         -**         [ Co-routine generated by this subroutine, shown above ]
   382         -**      S: yield X, at EOF goto E
   383         -**         if skip this row, goto C
   384         -**         if terminate loop, goto E
   385         -**         deal with this row
   386         -**      C: goto S
   387         -**      E:
   388         -*/
   389         -int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
   390         -  int regYield;       /* Register holding co-routine entry-point */
   391         -  int addrTop;        /* Top of the co-routine */
   392         -  int rc;             /* Result code */
   393         -  Vdbe *v;            /* VDBE under construction */
   394         -
   395         -  regYield = ++pParse->nMem;
   396         -  v = sqlite3GetVdbe(pParse);
   397         -  addrTop = sqlite3VdbeCurrentAddr(v) + 1;
   398         -  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
   399         -  sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
   400         -  rc = sqlite3Select(pParse, pSelect, pDest);
   401         -  assert( pParse->nErr==0 || rc );
   402         -  if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
   403         -  if( rc ) return rc;
   404         -  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
   405         -  sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
   406         -  return rc;
   407         -}
   408         -
   409    332   
   410    333   
   411    334   /* Forward declaration */
   412    335   static int xferOptimization(
   413    336     Parse *pParse,        /* Parser context */
   414    337     Table *pDest,         /* The table we are inserting into */
   415    338     Select *pSelect,      /* A SELECT statement to use as the data source */
................................................................................
   527    450     Index *pIdx;          /* For looping over indices of the table */
   528    451     int nColumn;          /* Number of columns in the data */
   529    452     int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
   530    453     int iDataCur = 0;     /* VDBE cursor that is the main data repository */
   531    454     int iIdxCur = 0;      /* First index cursor */
   532    455     int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
   533    456     int endOfLoop;        /* Label for the end of the insertion loop */
   534         -  int useTempTable = 0; /* Store SELECT results in intermediate table */
   535    457     int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
   536    458     int addrInsTop = 0;   /* Jump to label "D" */
   537    459     int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
   538         -  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
   539    460     SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
   540    461     int iDb;              /* Index of database holding TABLE */
   541    462     Db *pDb;              /* The database containing table being inserted into */
   542         -  int appendFlag = 0;   /* True if the insert is likely to be an append */
   543         -  int withoutRowid;     /* 0 for normal table.  1 for WITHOUT ROWID table */
          463  +  u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
          464  +  u8 appendFlag = 0;    /* True if the insert is likely to be an append */
          465  +  u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
          466  +  u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
   544    467     ExprList *pList = 0;  /* List of VALUES() to be inserted  */
   545    468   
   546    469     /* Register allocations */
   547    470     int regFromSelect = 0;/* Base register for data coming from SELECT */
   548    471     int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
   549    472     int regRowCount = 0;  /* Memory cell used for the row counter */
   550    473     int regIns;           /* Block of regs holding rowid+data being inserted */
................................................................................
   647    570     }
   648    571   #endif /* SQLITE_OMIT_XFER_OPT */
   649    572   
   650    573     /* If this is an AUTOINCREMENT table, look up the sequence number in the
   651    574     ** sqlite_sequence table and store it in memory cell regAutoinc.
   652    575     */
   653    576     regAutoinc = autoIncBegin(pParse, iDb, pTab);
          577  +
          578  +  /* Allocate registers for holding the rowid of the new row,
          579  +  ** the content of the new row, and the assemblied row record.
          580  +  */
          581  +  regRowid = regIns = pParse->nMem+1;
          582  +  pParse->nMem += pTab->nCol + 1;
          583  +  if( IsVirtual(pTab) ){
          584  +    regRowid++;
          585  +    pParse->nMem++;
          586  +  }
          587  +  regData = regRowid+1;
          588  +
          589  +  /* If the INSERT statement included an IDLIST term, then make sure
          590  +  ** all elements of the IDLIST really are columns of the table and 
          591  +  ** remember the column indices.
          592  +  **
          593  +  ** If the table has an INTEGER PRIMARY KEY column and that column
          594  +  ** is named in the IDLIST, then record in the ipkColumn variable
          595  +  ** the index into IDLIST of the primary key column.  ipkColumn is
          596  +  ** the index of the primary key as it appears in IDLIST, not as
          597  +  ** is appears in the original table.  (The index of the INTEGER
          598  +  ** PRIMARY KEY in the original table is pTab->iPKey.)
          599  +  */
          600  +  if( pColumn ){
          601  +    for(i=0; i<pColumn->nId; i++){
          602  +      pColumn->a[i].idx = -1;
          603  +    }
          604  +    for(i=0; i<pColumn->nId; i++){
          605  +      for(j=0; j<pTab->nCol; j++){
          606  +        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
          607  +          pColumn->a[i].idx = j;
          608  +          if( i!=j ) bIdListInOrder = 0;
          609  +          if( j==pTab->iPKey ){
          610  +            ipkColumn = i;  assert( !withoutRowid );
          611  +          }
          612  +          break;
          613  +        }
          614  +      }
          615  +      if( j>=pTab->nCol ){
          616  +        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
          617  +          ipkColumn = i;
          618  +        }else{
          619  +          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
          620  +              pTabList, 0, pColumn->a[i].zName);
          621  +          pParse->checkSchema = 1;
          622  +          goto insert_cleanup;
          623  +        }
          624  +      }
          625  +    }
          626  +  }
   654    627   
   655    628     /* Figure out how many columns of data are supplied.  If the data
   656    629     ** is coming from a SELECT statement, then generate a co-routine that
   657    630     ** produces a single row of the SELECT on each invocation.  The
   658    631     ** co-routine is the common header to the 3rd and 4th templates.
   659    632     */
   660    633     if( pSelect ){
   661    634       /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
   662         -    int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
   663         -    if( rc ) goto insert_cleanup;
          635  +    int regYield;       /* Register holding co-routine entry-point */
          636  +    int addrTop;        /* Top of the co-routine */
          637  +    int rc;             /* Result code */
   664    638   
          639  +    regYield = ++pParse->nMem;
          640  +    addrTop = sqlite3VdbeCurrentAddr(v) + 1;
          641  +    sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
          642  +    sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
          643  +    dest.iSdst = bIdListInOrder ? regData : 0;
          644  +    dest.nSdst = pTab->nCol;
          645  +    rc = sqlite3Select(pParse, pSelect, &dest);
   665    646       regFromSelect = dest.iSdst;
          647  +    assert( pParse->nErr==0 || rc );
          648  +    if( rc || db->mallocFailed ) goto insert_cleanup;
          649  +    sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
          650  +    sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
   666    651       assert( pSelect->pEList );
   667    652       nColumn = pSelect->pEList->nExpr;
   668         -    assert( dest.nSdst==nColumn );
   669    653   
   670    654       /* Set useTempTable to TRUE if the result of the SELECT statement
   671    655       ** should be written into a temporary table (template 4).  Set to
   672    656       ** FALSE if each output row of the SELECT can be written directly into
   673    657       ** the destination table (template 3).
   674    658       **
   675    659       ** A temp table must be used if the table being updated is also one
   676    660       ** of the tables being read by the SELECT statement.  Also use a 
   677    661       ** temp table in the case of row triggers.
   678    662       */
   679         -    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
          663  +    if( pTrigger || readsTable(pParse, iDb, pTab) ){
   680    664         useTempTable = 1;
   681    665       }
   682    666   
   683    667       if( useTempTable ){
   684    668         /* Invoke the coroutine to extract information from the SELECT
   685    669         ** and add it to a transient table srcTab.  The code generated
   686    670         ** here is from the 4th template:
................................................................................
   689    673         **      L: yield X, goto M at EOF
   690    674         **         insert row from R..R+n into temp table
   691    675         **         goto L
   692    676         **      M: ...
   693    677         */
   694    678         int regRec;          /* Register to hold packed record */
   695    679         int regTempRowid;    /* Register to hold temp table ROWID */
   696         -      int addrTop;         /* Label "L" */
          680  +      int addrL;           /* Label "L" */
   697    681   
   698    682         srcTab = pParse->nTab++;
   699    683         regRec = sqlite3GetTempReg(pParse);
   700    684         regTempRowid = sqlite3GetTempReg(pParse);
   701    685         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
   702         -      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
          686  +      addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
   703    687         sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
   704    688         sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
   705    689         sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
   706         -      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
   707         -      sqlite3VdbeJumpHere(v, addrTop);
          690  +      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
          691  +      sqlite3VdbeJumpHere(v, addrL);
   708    692         sqlite3ReleaseTempReg(pParse, regRec);
   709    693         sqlite3ReleaseTempReg(pParse, regTempRowid);
   710    694       }
   711    695     }else{
   712    696       /* This is the case if the data for the INSERT is coming from a VALUES
   713    697       ** clause
   714    698       */
................................................................................
   720    704       nColumn = pList ? pList->nExpr : 0;
   721    705       for(i=0; i<nColumn; i++){
   722    706         if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
   723    707           goto insert_cleanup;
   724    708         }
   725    709       }
   726    710     }
          711  +
          712  +  /* If there is no IDLIST term but the table has an integer primary
          713  +  ** key, the set the ipkColumn variable to the integer primary key 
          714  +  ** column index in the original table definition.
          715  +  */
          716  +  if( pColumn==0 && nColumn>0 ){
          717  +    ipkColumn = pTab->iPKey;
          718  +  }
   727    719   
   728    720     /* Make sure the number of columns in the source data matches the number
   729    721     ** of columns to be inserted into the table.
   730    722     */
   731    723     if( IsVirtual(pTab) ){
   732    724       for(i=0; i<pTab->nCol; i++){
   733    725         nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
................................................................................
   739    731          pTabList, 0, pTab->nCol-nHidden, nColumn);
   740    732       goto insert_cleanup;
   741    733     }
   742    734     if( pColumn!=0 && nColumn!=pColumn->nId ){
   743    735       sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
   744    736       goto insert_cleanup;
   745    737     }
   746         -
   747         -  /* If the INSERT statement included an IDLIST term, then make sure
   748         -  ** all elements of the IDLIST really are columns of the table and 
   749         -  ** remember the column indices.
   750         -  **
   751         -  ** If the table has an INTEGER PRIMARY KEY column and that column
   752         -  ** is named in the IDLIST, then record in the ipkColumn variable
   753         -  ** the index into IDLIST of the primary key column.  ipkColumn is
   754         -  ** the index of the primary key as it appears in IDLIST, not as
   755         -  ** is appears in the original table.  (The index of the INTEGER
   756         -  ** PRIMARY KEY in the original table is pTab->iPKey.)
   757         -  */
   758         -  if( pColumn ){
   759         -    for(i=0; i<pColumn->nId; i++){
   760         -      pColumn->a[i].idx = -1;
   761         -    }
   762         -    for(i=0; i<pColumn->nId; i++){
   763         -      for(j=0; j<pTab->nCol; j++){
   764         -        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
   765         -          pColumn->a[i].idx = j;
   766         -          if( j==pTab->iPKey ){
   767         -            ipkColumn = i;  assert( !withoutRowid );
   768         -          }
   769         -          break;
   770         -        }
   771         -      }
   772         -      if( j>=pTab->nCol ){
   773         -        if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
   774         -          ipkColumn = i;
   775         -        }else{
   776         -          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
   777         -              pTabList, 0, pColumn->a[i].zName);
   778         -          pParse->checkSchema = 1;
   779         -          goto insert_cleanup;
   780         -        }
   781         -      }
   782         -    }
   783         -  }
   784         -
   785         -  /* If there is no IDLIST term but the table has an integer primary
   786         -  ** key, the set the ipkColumn variable to the integer primary key 
   787         -  ** column index in the original table definition.
   788         -  */
   789         -  if( pColumn==0 && nColumn>0 ){
   790         -    ipkColumn = pTab->iPKey;
   791         -  }
   792    738       
   793    739     /* Initialize the count of rows to be inserted
   794    740     */
   795    741     if( db->flags & SQLITE_CountRows ){
   796    742       regRowCount = ++pParse->nMem;
   797    743       sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
   798    744     }
................................................................................
   818    764       **
   819    765       **         rewind temp table, if empty goto D
   820    766       **      C: loop over rows of intermediate table
   821    767       **           transfer values form intermediate table into <table>
   822    768       **         end loop
   823    769       **      D: ...
   824    770       */
   825         -    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
          771  +    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
   826    772       addrCont = sqlite3VdbeCurrentAddr(v);
   827    773     }else if( pSelect ){
   828    774       /* This block codes the top of loop only.  The complete loop is the
   829    775       ** following pseudocode (template 3):
   830    776       **
   831    777       **      C: yield X, at EOF goto D
   832    778       **         insert the select result into <table> from R..R+n
   833    779       **         goto C
   834    780       **      D: ...
   835    781       */
   836    782       addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
          783  +    VdbeCoverage(v);
   837    784     }
   838    785   
   839         -  /* Allocate registers for holding the rowid of the new row,
   840         -  ** the content of the new row, and the assemblied row record.
   841         -  */
   842         -  regRowid = regIns = pParse->nMem+1;
   843         -  pParse->nMem += pTab->nCol + 1;
   844         -  if( IsVirtual(pTab) ){
   845         -    regRowid++;
   846         -    pParse->nMem++;
   847         -  }
   848         -  regData = regRowid+1;
   849         -
   850    786     /* Run the BEFORE and INSTEAD OF triggers, if there are any
   851    787     */
   852    788     endOfLoop = sqlite3VdbeMakeLabel(v);
   853    789     if( tmask & TRIGGER_BEFORE ){
   854    790       int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
   855    791   
   856    792       /* build the NEW.* reference row.  Note that if there is an INTEGER
................................................................................
   866    802         assert( !withoutRowid );
   867    803         if( useTempTable ){
   868    804           sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
   869    805         }else{
   870    806           assert( pSelect==0 );  /* Otherwise useTempTable is true */
   871    807           sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
   872    808         }
   873         -      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
          809  +      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
   874    810         sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
   875    811         sqlite3VdbeJumpHere(v, j1);
   876         -      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
          812  +      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
   877    813       }
   878    814   
   879    815       /* Cannot have triggers on a virtual table. If it were possible,
   880    816       ** this block would have to account for hidden column.
   881    817       */
   882    818       assert( !IsVirtual(pTab) );
   883    819   
................................................................................
   903    839   
   904    840       /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
   905    841       ** do not attempt any conversions before assembling the record.
   906    842       ** If this is a real table, attempt conversions as required by the
   907    843       ** table column affinities.
   908    844       */
   909    845       if( !isView ){
   910         -      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
   911         -      sqlite3TableAffinityStr(v, pTab);
          846  +      sqlite3TableAffinity(v, pTab, regCols+1);
   912    847       }
   913    848   
   914    849       /* Fire BEFORE or INSTEAD OF triggers */
   915    850       sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
   916    851           pTab, regCols-pTab->nCol-1, onError, endOfLoop);
   917    852   
   918    853       sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
................................................................................
   926    861         /* The row that the VUpdate opcode will delete: none */
   927    862         sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
   928    863       }
   929    864       if( ipkColumn>=0 ){
   930    865         if( useTempTable ){
   931    866           sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
   932    867         }else if( pSelect ){
   933         -        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+ipkColumn, regRowid);
          868  +        sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
   934    869         }else{
   935    870           VdbeOp *pOp;
   936    871           sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
   937    872           pOp = sqlite3VdbeGetOp(v, -1);
   938    873           if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
   939    874             appendFlag = 1;
   940    875             pOp->opcode = OP_NewRowid;
................................................................................
   945    880         }
   946    881         /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
   947    882         ** to generate a unique primary key value.
   948    883         */
   949    884         if( !appendFlag ){
   950    885           int j1;
   951    886           if( !IsVirtual(pTab) ){
   952         -          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
          887  +          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
   953    888             sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   954    889             sqlite3VdbeJumpHere(v, j1);
   955    890           }else{
   956    891             j1 = sqlite3VdbeCurrentAddr(v);
   957         -          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
          892  +          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
   958    893           }
   959         -        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
          894  +        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
   960    895         }
   961    896       }else if( IsVirtual(pTab) || withoutRowid ){
   962    897         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
   963    898       }else{
   964    899         sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
   965    900         appendFlag = 1;
   966    901       }
................................................................................
   972    907       nHidden = 0;
   973    908       for(i=0; i<pTab->nCol; i++){
   974    909         int iRegStore = regRowid+1+i;
   975    910         if( i==pTab->iPKey ){
   976    911           /* The value of the INTEGER PRIMARY KEY column is always a NULL.
   977    912           ** Whenever this column is read, the rowid will be substituted
   978    913           ** in its place.  Hence, fill this column with a NULL to avoid
   979         -        ** taking up data space with information that will never be used. */
   980         -        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
          914  +        ** taking up data space with information that will never be used.
          915  +        ** As there may be shallow copies of this value, make it a soft-NULL */
          916  +        sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
   981    917           continue;
   982    918         }
   983    919         if( pColumn==0 ){
   984    920           if( IsHiddenColumn(&pTab->aCol[i]) ){
   985    921             assert( IsVirtual(pTab) );
   986    922             j = -1;
   987    923             nHidden++;
................................................................................
   990    926           }
   991    927         }else{
   992    928           for(j=0; j<pColumn->nId; j++){
   993    929             if( pColumn->a[j].idx==i ) break;
   994    930           }
   995    931         }
   996    932         if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
   997         -        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
          933  +        sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
   998    934         }else if( useTempTable ){
   999    935           sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
  1000    936         }else if( pSelect ){
  1001         -        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
          937  +        if( regFromSelect!=regData ){
          938  +          sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
          939  +        }
  1002    940         }else{
  1003    941           sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  1004    942         }
  1005    943       }
  1006    944   
  1007    945       /* Generate code to check constraints and generate index keys and
  1008    946       ** do the insertion.
................................................................................
  1040    978     }
  1041    979   
  1042    980     /* The bottom of the main insertion loop, if the data source
  1043    981     ** is a SELECT statement.
  1044    982     */
  1045    983     sqlite3VdbeResolveLabel(v, endOfLoop);
  1046    984     if( useTempTable ){
  1047         -    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
          985  +    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  1048    986       sqlite3VdbeJumpHere(v, addrInsTop);
  1049    987       sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  1050    988     }else if( pSelect ){
  1051    989       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  1052    990       sqlite3VdbeJumpHere(v, addrInsTop);
  1053    991     }
  1054    992   
................................................................................
  1207   1145     int onError;         /* Conflict resolution strategy */
  1208   1146     int j1;              /* Addresss of jump instruction */
  1209   1147     int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  1210   1148     int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  1211   1149     int ipkTop = 0;      /* Top of the rowid change constraint check */
  1212   1150     int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
  1213   1151     u8 isUpdate;         /* True if this is an UPDATE operation */
         1152  +  u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
  1214   1153     int regRowid = -1;   /* Register holding ROWID value */
  1215   1154   
  1216   1155     isUpdate = regOldData!=0;
  1217   1156     db = pParse->db;
  1218   1157     v = sqlite3GetVdbe(pParse);
  1219   1158     assert( v!=0 );
  1220   1159     assert( pTab->pSelect==0 );  /* This table is not a VIEW */
................................................................................
  1261   1200         case OE_Rollback:
  1262   1201         case OE_Fail: {
  1263   1202           char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  1264   1203                                       pTab->aCol[i].zName);
  1265   1204           sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  1266   1205                             regNewData+1+i, zMsg, P4_DYNAMIC);
  1267   1206           sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
         1207  +        VdbeCoverage(v);
  1268   1208           break;
  1269   1209         }
  1270   1210         case OE_Ignore: {
  1271   1211           sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
         1212  +        VdbeCoverage(v);
  1272   1213           break;
  1273   1214         }
  1274   1215         default: {
  1275   1216           assert( onError==OE_Replace );
  1276         -        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
         1217  +        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
  1277   1218           sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  1278   1219           sqlite3VdbeJumpHere(v, j1);
  1279   1220           break;
  1280   1221         }
  1281   1222       }
  1282   1223     }
  1283   1224   
................................................................................
  1321   1262       }
  1322   1263   
  1323   1264       if( isUpdate ){
  1324   1265         /* pkChng!=0 does not mean that the rowid has change, only that
  1325   1266         ** it might have changed.  Skip the conflict logic below if the rowid
  1326   1267         ** is unchanged. */
  1327   1268         sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
         1269  +      sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
         1270  +      VdbeCoverage(v);
  1328   1271       }
  1329   1272   
  1330   1273       /* If the response to a rowid conflict is REPLACE but the response
  1331   1274       ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  1332   1275       ** to defer the running of the rowid conflict checking until after
  1333   1276       ** the UNIQUE constraints have run.
  1334   1277       */
................................................................................
  1340   1283           }
  1341   1284         }
  1342   1285       }
  1343   1286   
  1344   1287       /* Check to see if the new rowid already exists in the table.  Skip
  1345   1288       ** the following conflict logic if it does not. */
  1346   1289       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
         1290  +    VdbeCoverage(v);
  1347   1291   
  1348   1292       /* Generate code that deals with a rowid collision */
  1349   1293       switch( onError ){
  1350   1294         default: {
  1351   1295           onError = OE_Abort;
  1352   1296           /* Fall thru into the next case */
  1353   1297         }
................................................................................
  1430   1374     for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  1431   1375       int regIdx;          /* Range of registers hold conent for pIdx */
  1432   1376       int regR;            /* Range of registers holding conflicting PK */
  1433   1377       int iThisCur;        /* Cursor for this UNIQUE index */
  1434   1378       int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
  1435   1379   
  1436   1380       if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
         1381  +    if( bAffinityDone==0 ){
         1382  +      sqlite3TableAffinity(v, pTab, regNewData+1);
         1383  +      bAffinityDone = 1;
         1384  +    }
  1437   1385       iThisCur = iIdxCur+ix;
  1438   1386       addrUniqueOk = sqlite3VdbeMakeLabel(v);
  1439   1387   
  1440   1388       /* Skip partial indices for which the WHERE clause is not true */
  1441   1389       if( pIdx->pPartIdxWhere ){
  1442   1390         sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  1443   1391         pParse->ckBase = regNewData+1;
................................................................................
  1460   1408         }else{
  1461   1409           x = iField + regNewData + 1;
  1462   1410         }
  1463   1411         sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
  1464   1412         VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  1465   1413       }
  1466   1414       sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  1467         -    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  1468   1415       VdbeComment((v, "for %s", pIdx->zName));
  1469   1416       sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  1470   1417   
  1471   1418       /* In an UPDATE operation, if this index is the PRIMARY KEY index 
  1472   1419       ** of a WITHOUT ROWID table and there has been no change the
  1473   1420       ** primary key, then no collision is possible.  The collision detection
  1474   1421       ** logic below can all be skipped. */
................................................................................
  1488   1435         onError = overrideError;
  1489   1436       }else if( onError==OE_Default ){
  1490   1437         onError = OE_Abort;
  1491   1438       }
  1492   1439       
  1493   1440       /* Check to see if the new index entry will be unique */
  1494   1441       sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  1495         -                         regIdx, pIdx->nKeyCol);
         1442  +                         regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  1496   1443   
  1497   1444       /* Generate code to handle collisions */
  1498   1445       regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  1499   1446       if( isUpdate || onError==OE_Replace ){
  1500   1447         if( HasRowid(pTab) ){
  1501   1448           sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  1502   1449           /* Conflict only if the rowid of the existing index entry
  1503   1450           ** is different from old-rowid */
  1504   1451           if( isUpdate ){
  1505   1452             sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
         1453  +          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
         1454  +          VdbeCoverage(v);
  1506   1455           }
  1507   1456         }else{
  1508   1457           int x;
  1509   1458           /* Extract the PRIMARY KEY from the end of the index entry and
  1510   1459           ** store it in registers regR..regR+nPk-1 */
  1511   1460           if( pIdx!=pPk ){
  1512   1461             for(i=0; i<pPk->nKeyCol; i++){
................................................................................
  1534   1483               if( i==(pPk->nKeyCol-1) ){
  1535   1484                 addrJump = addrUniqueOk;
  1536   1485                 op = OP_Eq;
  1537   1486               }
  1538   1487               sqlite3VdbeAddOp4(v, op, 
  1539   1488                   regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  1540   1489               );
         1490  +            sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
         1491  +            VdbeCoverageIf(v, op==OP_Eq);
         1492  +            VdbeCoverageIf(v, op==OP_Ne);
  1541   1493             }
  1542   1494           }
  1543   1495         }
  1544   1496       }
  1545   1497   
  1546   1498       /* Generate code that executes if the new index entry is not unique */
  1547   1499       assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
................................................................................
  1605   1557   ){
  1606   1558     Vdbe *v;            /* Prepared statements under construction */
  1607   1559     Index *pIdx;        /* An index being inserted or updated */
  1608   1560     u8 pik_flags;       /* flag values passed to the btree insert */
  1609   1561     int regData;        /* Content registers (after the rowid) */
  1610   1562     int regRec;         /* Register holding assemblied record for the table */
  1611   1563     int i;              /* Loop counter */
         1564  +  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  1612   1565   
  1613   1566     v = sqlite3GetVdbe(pParse);
  1614   1567     assert( v!=0 );
  1615   1568     assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  1616   1569     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  1617   1570       if( aRegIdx[i]==0 ) continue;
         1571  +    bAffinityDone = 1;
  1618   1572       if( pIdx->pPartIdxWhere ){
  1619   1573         sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
         1574  +      VdbeCoverage(v);
  1620   1575       }
  1621   1576       sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  1622   1577       pik_flags = 0;
  1623   1578       if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  1624   1579       if( pIdx->autoIndex==2 && !HasRowid(pTab) ){
  1625   1580         assert( pParse->nested==0 );
  1626   1581         pik_flags |= OPFLAG_NCHANGE;
................................................................................
  1627   1582       }
  1628   1583       if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
  1629   1584     }
  1630   1585     if( !HasRowid(pTab) ) return;
  1631   1586     regData = regNewData + 1;
  1632   1587     regRec = sqlite3GetTempReg(pParse);
  1633   1588     sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  1634         -  sqlite3TableAffinityStr(v, pTab);
         1589  +  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  1635   1590     sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  1636   1591     if( pParse->nested ){
  1637   1592       pik_flags = 0;
  1638   1593     }else{
  1639   1594       pik_flags = OPFLAG_NCHANGE;
  1640   1595       pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  1641   1596     }
................................................................................
  1996   1951       **     of index entries might need to change.)
  1997   1952       **
  1998   1953       ** (2) The destination has a unique index.  (The xfer optimization 
  1999   1954       **     is unable to test uniqueness.)
  2000   1955       **
  2001   1956       ** (3) onError is something other than OE_Abort and OE_Rollback.
  2002   1957       */
  2003         -    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
         1958  +    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  2004   1959       emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  2005   1960       sqlite3VdbeJumpHere(v, addr1);
  2006   1961     }
  2007   1962     if( HasRowid(pSrc) ){
  2008   1963       sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  2009         -    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
         1964  +    emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  2010   1965       if( pDest->iPKey>=0 ){
  2011   1966         addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  2012   1967         addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
         1968  +      VdbeCoverage(v);
  2013   1969         sqlite3RowidConstraint(pParse, onError, pDest);
  2014   1970         sqlite3VdbeJumpHere(v, addr2);
  2015   1971         autoIncStep(pParse, regAutoinc, regRowid);
  2016   1972       }else if( pDest->pIndex==0 ){
  2017   1973         addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  2018   1974       }else{
  2019   1975         addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  2020   1976         assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  2021   1977       }
  2022   1978       sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  2023   1979       sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  2024   1980       sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  2025   1981       sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
  2026         -    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
         1982  +    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  2027   1983       sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  2028   1984       sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  2029   1985     }else{
  2030   1986       sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  2031   1987       sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  2032   1988     }
  2033   1989     for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
................................................................................
  2038   1994       sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  2039   1995       sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  2040   1996       VdbeComment((v, "%s", pSrcIdx->zName));
  2041   1997       sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  2042   1998       sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  2043   1999       sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  2044   2000       VdbeComment((v, "%s", pDestIdx->zName));
  2045         -    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
         2001  +    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  2046   2002       sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  2047   2003       sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  2048         -    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
         2004  +    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  2049   2005       sqlite3VdbeJumpHere(v, addr1);
  2050   2006       sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  2051   2007       sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  2052   2008     }
  2053   2009     if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  2054   2010     sqlite3ReleaseTempReg(pParse, regRowid);
  2055   2011     sqlite3ReleaseTempReg(pParse, regData);

Changes to src/main.c.

  3324   3324       ** that demonstrat invariants on well-formed database files.
  3325   3325       */
  3326   3326       case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  3327   3327         sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  3328   3328         break;
  3329   3329       }
  3330   3330   
         3331  +
         3332  +    /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
         3333  +    **
         3334  +    ** Set the VDBE coverage callback function to xCallback with context 
         3335  +    ** pointer ptr.
         3336  +    */
         3337  +    case SQLITE_TESTCTRL_VDBE_COVERAGE: {
         3338  +#ifdef SQLITE_VDBE_COVERAGE
         3339  +      typedef void (*branch_callback)(void*,int,u8,u8);
         3340  +      sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
         3341  +      sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
         3342  +#endif
         3343  +      break;
         3344  +    }
         3345  +
  3331   3346     }
  3332   3347     va_end(ap);
  3333   3348   #endif /* SQLITE_OMIT_BUILTIN_TEST */
  3334   3349     return rc;
  3335   3350   }
  3336   3351   
  3337   3352   /*

Changes to src/mem5.c.

   270    270     mem5.nAlloc++;
   271    271     mem5.totalAlloc += iFullSz;
   272    272     mem5.totalExcess += iFullSz - nByte;
   273    273     mem5.currentCount++;
   274    274     mem5.currentOut += iFullSz;
   275    275     if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
   276    276     if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
          277  +
          278  +#ifdef SQLITE_DEBUG
          279  +  /* Make sure the allocated memory does not assume that it is set to zero
          280  +  ** or retains a value from a previous allocation */
          281  +  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
          282  +#endif
   277    283   
   278    284     /* Return a pointer to the allocated memory. */
   279    285     return (void*)&mem5.zPool[i*mem5.szAtom];
   280    286   }
   281    287   
   282    288   /*
   283    289   ** Free an outstanding memory allocation.
................................................................................
   328    334         iBlock = iBuddy;
   329    335       }else{
   330    336         mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
   331    337         mem5.aCtrl[iBuddy] = 0;
   332    338       }
   333    339       size *= 2;
   334    340     }
          341  +
          342  +#ifdef SQLITE_DEBUG
          343  +  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
          344  +  ** not used after being freed */
          345  +  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
          346  +#endif
          347  +
   335    348     memsys5Link(iBlock, iLogsize);
   336    349   }
   337    350   
   338    351   /*
   339    352   ** Allocate nBytes of memory.
   340    353   */
   341    354   static void *memsys5Malloc(int nBytes){

Changes to src/os_win.c.

  5131   5131   }
  5132   5132   
  5133   5133   #ifndef SQLITE_OMIT_LOAD_EXTENSION
  5134   5134   /*
  5135   5135   ** Interfaces for opening a shared library, finding entry points
  5136   5136   ** within the shared library, and closing the shared library.
  5137   5137   */
  5138         -/*
  5139         -** Interfaces for opening a shared library, finding entry points
  5140         -** within the shared library, and closing the shared library.
  5141         -*/
  5142   5138   static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  5143   5139     HANDLE h;
  5144   5140     void *zConverted = winConvertFromUtf8Filename(zFilename);
  5145   5141     UNUSED_PARAMETER(pVfs);
  5146   5142     if( zConverted==0 ){
         5143  +    OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  5147   5144       return 0;
  5148   5145     }
  5149   5146     if( osIsNT() ){
  5150   5147   #if SQLITE_OS_WINRT
  5151   5148       h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  5152   5149   #else
  5153   5150       h = osLoadLibraryW((LPCWSTR)zConverted);
................................................................................
  5154   5151   #endif
  5155   5152     }
  5156   5153   #ifdef SQLITE_WIN32_HAS_ANSI
  5157   5154     else{
  5158   5155       h = osLoadLibraryA((char*)zConverted);
  5159   5156     }
  5160   5157   #endif
         5158  +  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  5161   5159     sqlite3_free(zConverted);
  5162   5160     return (void*)h;
  5163   5161   }
  5164   5162   static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  5165   5163     UNUSED_PARAMETER(pVfs);
  5166   5164     winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  5167   5165   }
  5168   5166   static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
         5167  +  FARPROC proc;
  5169   5168     UNUSED_PARAMETER(pVfs);
  5170         -  return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
         5169  +  proc = osGetProcAddressA((HANDLE)pH, zSym);
         5170  +  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
         5171  +           (void*)pH, zSym, (void*)proc));
         5172  +  return (void(*)(void))proc;
  5171   5173   }
  5172   5174   static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  5173   5175     UNUSED_PARAMETER(pVfs);
  5174   5176     osFreeLibrary((HANDLE)pHandle);
         5177  +  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  5175   5178   }
  5176   5179   #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  5177   5180     #define winDlOpen  0
  5178   5181     #define winDlError 0
  5179   5182     #define winDlSym   0
  5180   5183     #define winDlClose 0
  5181   5184   #endif

Changes to src/parse.y.

   433    433     }
   434    434     A = p;
   435    435   }
   436    436   
   437    437   selectnowith(A) ::= oneselect(X).                      {A = X;}
   438    438   %ifndef SQLITE_OMIT_COMPOUND_SELECT
   439    439   selectnowith(A) ::= selectnowith(X) multiselect_op(Y) oneselect(Z).  {
   440         -  if( Z ){
   441         -    Z->op = (u8)Y;
   442         -    Z->pPrior = X;
          440  +  Select *pRhs = Z;
          441  +  if( pRhs && pRhs->pPrior ){
          442  +    SrcList *pFrom;
          443  +    Token x;
          444  +    x.n = 0;
          445  +    pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
          446  +    pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
          447  +  }
          448  +  if( pRhs ){
          449  +    pRhs->op = (u8)Y;
          450  +    pRhs->pPrior = X;
   443    451       if( Y!=TK_ALL ) pParse->hasCompound = 1;
   444    452     }else{
   445    453       sqlite3SelectDelete(pParse->db, X);
   446    454     }
   447         -  A = Z;
          455  +  A = pRhs;
   448    456   }
   449    457   %type multiselect_op {int}
   450    458   multiselect_op(A) ::= UNION(OP).             {A = @OP;}
   451    459   multiselect_op(A) ::= UNION ALL.             {A = TK_ALL;}
   452    460   multiselect_op(A) ::= EXCEPT|INTERSECT(OP).  {A = @OP;}
   453    461   %endif SQLITE_OMIT_COMPOUND_SELECT
   454    462   oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)

Changes to src/pragma.c.

   820    820     ** Older versions of SQLite would set the default cache size to a
   821    821     ** negative number to indicate synchronous=OFF.  These days, synchronous
   822    822     ** is always on by default regardless of the sign of the default cache
   823    823     ** size.  But continue to take the absolute value of the default cache
   824    824     ** size of historical compatibility.
   825    825     */
   826    826     case PragTyp_DEFAULT_CACHE_SIZE: {
          827  +    static const int iLn = __LINE__+2;
   827    828       static const VdbeOpList getCacheSize[] = {
   828    829         { OP_Transaction, 0, 0,        0},                         /* 0 */
   829    830         { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
   830    831         { OP_IfPos,       1, 8,        0},
   831    832         { OP_Integer,     0, 2,        0},
   832    833         { OP_Subtract,    1, 2,        1},
   833    834         { OP_IfPos,       1, 8,        0},
................................................................................
   837    838       };
   838    839       int addr;
   839    840       sqlite3VdbeUsesBtree(v, iDb);
   840    841       if( !zRight ){
   841    842         sqlite3VdbeSetNumCols(v, 1);
   842    843         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
   843    844         pParse->nMem += 2;
   844         -      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
          845  +      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
   845    846         sqlite3VdbeChangeP1(v, addr, iDb);
   846    847         sqlite3VdbeChangeP1(v, addr+1, iDb);
   847    848         sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
   848    849       }else{
   849    850         int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
   850    851         sqlite3BeginWriteOperation(pParse, 0, iDb);
   851    852         sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
................................................................................
  1082   1083         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  1083   1084         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  1084   1085           /* When setting the auto_vacuum mode to either "full" or 
  1085   1086           ** "incremental", write the value of meta[6] in the database
  1086   1087           ** file. Before writing to meta[6], check that meta[3] indicates
  1087   1088           ** that this really is an auto-vacuum capable database.
  1088   1089           */
         1090  +        static const int iLn = __LINE__+2;
  1089   1091           static const VdbeOpList setMeta6[] = {
  1090   1092             { OP_Transaction,    0,         1,                 0},    /* 0 */
  1091   1093             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
  1092   1094             { OP_If,             1,         0,                 0},    /* 2 */
  1093   1095             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
  1094   1096             { OP_Integer,        0,         1,                 0},    /* 4 */
  1095   1097             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
  1096   1098           };
  1097   1099           int iAddr;
  1098         -        iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
         1100  +        iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  1099   1101           sqlite3VdbeChangeP1(v, iAddr, iDb);
  1100   1102           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  1101   1103           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  1102   1104           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  1103   1105           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  1104   1106           sqlite3VdbeUsesBtree(v, iDb);
  1105   1107         }
................................................................................
  1117   1119     case PragTyp_INCREMENTAL_VACUUM: {
  1118   1120       int iLimit, addr;
  1119   1121       if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  1120   1122         iLimit = 0x7fffffff;
  1121   1123       }
  1122   1124       sqlite3BeginWriteOperation(pParse, 0, iDb);
  1123   1125       sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  1124         -    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
         1126  +    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  1125   1127       sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  1126   1128       sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  1127         -    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
         1129  +    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  1128   1130       sqlite3VdbeJumpHere(v, addr);
  1129   1131       break;
  1130   1132     }
  1131   1133   #endif
  1132   1134   
  1133   1135   #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  1134   1136     /*
................................................................................
  1691   1693             k = 0;
  1692   1694             break;
  1693   1695           }
  1694   1696         }
  1695   1697         assert( pParse->nErr>0 || pFK==0 );
  1696   1698         if( pFK ) break;
  1697   1699         if( pParse->nTab<i ) pParse->nTab = i;
  1698         -      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
         1700  +      addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  1699   1701         for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  1700   1702           pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  1701   1703           pIdx = 0;
  1702   1704           aiCols = 0;
  1703   1705           if( pParent ){
  1704   1706             x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  1705   1707             assert( x==0 );
................................................................................
  1707   1709           addrOk = sqlite3VdbeMakeLabel(v);
  1708   1710           if( pParent && pIdx==0 ){
  1709   1711             int iKey = pFK->aCol[0].iFrom;
  1710   1712             assert( iKey>=0 && iKey<pTab->nCol );
  1711   1713             if( iKey!=pTab->iPKey ){
  1712   1714               sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  1713   1715               sqlite3ColumnDefault(v, pTab, iKey, regRow);
  1714         -            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
  1715         -            sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  1716         -               sqlite3VdbeCurrentAddr(v)+3);
         1716  +            sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
         1717  +            sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow, 
         1718  +               sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  1717   1719             }else{
  1718   1720               sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  1719   1721             }
  1720         -          sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
         1722  +          sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  1721   1723             sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  1722   1724             sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  1723   1725           }else{
  1724   1726             for(j=0; j<pFK->nCol; j++){
  1725   1727               sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  1726   1728                               aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  1727         -            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
         1729  +            sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  1728   1730             }
  1729   1731             if( pParent ){
  1730         -            sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
  1731         -            sqlite3VdbeChangeP4(v, -1,
  1732         -                     sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
         1732  +            sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
         1733  +                              sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
  1733   1734               sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
         1735  +            VdbeCoverage(v);
  1734   1736             }
  1735   1737           }
  1736   1738           sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  1737   1739           sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0, 
  1738   1740                             pFK->zTo, P4_TRANSIENT);
  1739   1741           sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  1740   1742           sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  1741   1743           sqlite3VdbeResolveLabel(v, addrOk);
  1742   1744           sqlite3DbFree(db, aiCols);
  1743   1745         }
  1744         -      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
         1746  +      sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  1745   1747         sqlite3VdbeJumpHere(v, addrTop);
  1746   1748       }
  1747   1749     }
  1748   1750     break;
  1749   1751   #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  1750   1752   #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  1751   1753   
................................................................................
  1784   1786     case PragTyp_INTEGRITY_CHECK: {
  1785   1787       int i, j, addr, mxErr;
  1786   1788   
  1787   1789       /* Code that appears at the end of the integrity check.  If no error
  1788   1790       ** messages have been generated, output OK.  Otherwise output the
  1789   1791       ** error message
  1790   1792       */
         1793  +    static const int iLn = __LINE__+2;
  1791   1794       static const VdbeOpList endCode[] = {
  1792   1795         { OP_AddImm,      1, 0,        0},    /* 0 */
  1793   1796         { OP_IfNeg,       1, 0,        0},    /* 1 */
  1794   1797         { OP_String8,     0, 3,        0},    /* 2 */
  1795   1798         { OP_ResultRow,   3, 1,        0},
  1796   1799       };
  1797   1800   
................................................................................
  1832   1835         int cnt = 0;
  1833   1836   
  1834   1837         if( OMIT_TEMPDB && i==1 ) continue;
  1835   1838         if( iDb>=0 && i!=iDb ) continue;
  1836   1839   
  1837   1840         sqlite3CodeVerifySchema(pParse, i);
  1838   1841         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
         1842  +      VdbeCoverage(v);
  1839   1843         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  1840   1844         sqlite3VdbeJumpHere(v, addr);
  1841   1845   
  1842   1846         /* Do an integrity check of the B-Tree
  1843   1847         **
  1844   1848         ** Begin by filling registers 2, 3, ... with the root pages numbers
  1845   1849         ** for all tables and indices in the database.
................................................................................
  1863   1867   
  1864   1868         /* Make sure sufficient number of registers have been allocated */
  1865   1869         pParse->nMem = MAX( pParse->nMem, cnt+8 );
  1866   1870   
  1867   1871         /* Do the b-tree integrity checks */
  1868   1872         sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  1869   1873         sqlite3VdbeChangeP5(v, (u8)i);
  1870         -      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
         1874  +      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  1871   1875         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  1872   1876            sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  1873   1877            P4_DYNAMIC);
  1874   1878         sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  1875   1879         sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  1876   1880         sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  1877   1881         sqlite3VdbeJumpHere(v, addr);
................................................................................
  1885   1889           int loopTop;
  1886   1890           int iDataCur, iIdxCur;
  1887   1891           int r1 = -1;
  1888   1892   
  1889   1893           if( pTab->pIndex==0 ) continue;
  1890   1894           pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  1891   1895           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
         1896  +        VdbeCoverage(v);
  1892   1897           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  1893   1898           sqlite3VdbeJumpHere(v, addr);
  1894   1899           sqlite3ExprCacheClear(pParse);
  1895   1900           sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
  1896   1901                                      1, 0, &iDataCur, &iIdxCur);
  1897   1902           sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  1898   1903           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  1899   1904             sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  1900   1905           }
  1901   1906           pParse->nMem = MAX(pParse->nMem, 8+j);
  1902         -        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0);
         1907  +        sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  1903   1908           loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  1904   1909           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  1905   1910             int jmp2, jmp3, jmp4;
  1906   1911             if( pPk==pIdx ) continue;
  1907   1912             r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  1908   1913                                          pPrior, r1);
  1909   1914             pPrior = pIdx;
  1910   1915             sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
  1911   1916             jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, 0, r1,
  1912         -                                      pIdx->nColumn);
         1917  +                                      pIdx->nColumn); VdbeCoverage(v);
  1913   1918             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  1914   1919             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
  1915   1920             sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  1916   1921             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, " missing from index ",
  1917   1922                               P4_STATIC);
  1918   1923             sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  1919   1924             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, pIdx->zName, P4_TRANSIENT);
  1920   1925             sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  1921   1926             sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  1922         -          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
         1927  +          jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  1923   1928             sqlite3VdbeAddOp0(v, OP_Halt);
  1924   1929             sqlite3VdbeJumpHere(v, jmp4);
  1925   1930             sqlite3VdbeJumpHere(v, jmp2);
  1926   1931             sqlite3VdbeResolveLabel(v, jmp3);
  1927   1932           }
  1928         -        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop);
         1933  +        sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  1929   1934           sqlite3VdbeJumpHere(v, loopTop-1);
  1930   1935   #ifndef SQLITE_OMIT_BTREECOUNT
  1931   1936           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, 
  1932   1937                        "wrong # of entries in index ", P4_STATIC);
  1933   1938           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  1934   1939             if( pPk==pIdx ) continue;
  1935   1940             addr = sqlite3VdbeCurrentAddr(v);
  1936         -          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
         1941  +          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  1937   1942             sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  1938   1943             sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  1939         -          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3);
         1944  +          sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
         1945  +          sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  1940   1946             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  1941   1947             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  1942   1948             sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  1943   1949             sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  1944   1950           }
  1945   1951   #endif /* SQLITE_OMIT_BTREECOUNT */
  1946   1952         } 
  1947   1953       }
  1948         -    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
         1954  +    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  1949   1955       sqlite3VdbeChangeP2(v, addr, -mxErr);
  1950   1956       sqlite3VdbeJumpHere(v, addr+1);
  1951   1957       sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  1952   1958     }
  1953   1959     break;
  1954   1960   #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  1955   1961   
................................................................................
  2079   2085       if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  2080   2086         /* Write the specified cookie value */
  2081   2087         static const VdbeOpList setCookie[] = {
  2082   2088           { OP_Transaction,    0,  1,  0},    /* 0 */
  2083   2089           { OP_Integer,        0,  1,  0},    /* 1 */
  2084   2090           { OP_SetCookie,      0,  0,  1},    /* 2 */
  2085   2091         };
  2086         -      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
         2092  +      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  2087   2093         sqlite3VdbeChangeP1(v, addr, iDb);
  2088   2094         sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  2089   2095         sqlite3VdbeChangeP1(v, addr+2, iDb);
  2090   2096         sqlite3VdbeChangeP2(v, addr+2, iCookie);
  2091   2097       }else{
  2092   2098         /* Read the specified cookie value */
  2093   2099         static const VdbeOpList readCookie[] = {
  2094   2100           { OP_Transaction,     0,  0,  0},    /* 0 */
  2095   2101           { OP_ReadCookie,      0,  1,  0},    /* 1 */
  2096   2102           { OP_ResultRow,       1,  1,  0}
  2097   2103         };
  2098         -      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
         2104  +      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
  2099   2105         sqlite3VdbeChangeP1(v, addr, iDb);
  2100   2106         sqlite3VdbeChangeP1(v, addr+1, iDb);
  2101   2107         sqlite3VdbeChangeP3(v, addr+1, iCookie);
  2102   2108         sqlite3VdbeSetNumCols(v, 1);
  2103   2109         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  2104   2110       }
  2105   2111     }

Changes to src/resolve.c.

   333    333         assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
   334    334         if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
   335    335           pExpr->iTable = 1;
   336    336           pTab = pParse->pTriggerTab;
   337    337         }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
   338    338           pExpr->iTable = 0;
   339    339           pTab = pParse->pTriggerTab;
          340  +      }else{
          341  +        pTab = 0;
   340    342         }
   341    343   
   342    344         if( pTab ){ 
   343    345           int iCol;
   344    346           pSchema = pTab->pSchema;
   345    347           cntTab++;
   346    348           for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
................................................................................
   376    378         }
   377    379       }
   378    380   #endif /* !defined(SQLITE_OMIT_TRIGGER) */
   379    381   
   380    382       /*
   381    383       ** Perhaps the name is a reference to the ROWID
   382    384       */
   383         -    assert( pTab!=0 || cntTab==0 );
   384         -    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
          385  +    if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
          386  +     && HasRowid(pMatch->pTab) ){
   385    387         cnt = 1;
   386    388         pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
   387    389         pExpr->affinity = SQLITE_AFF_INTEGER;
   388    390       }
   389    391   
   390    392       /*
   391    393       ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z

Changes to src/select.c.

   451    451       int addr1, addr2;
   452    452       int iLimit;
   453    453       if( pSelect->iOffset ){
   454    454         iLimit = pSelect->iOffset+1;
   455    455       }else{
   456    456         iLimit = pSelect->iLimit;
   457    457       }
   458         -    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
          458  +    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
   459    459       sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
   460    460       addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
   461    461       sqlite3VdbeJumpHere(v, addr1);
   462    462       sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
   463    463       sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
   464    464       sqlite3VdbeJumpHere(v, addr2);
   465    465     }
................................................................................
   472    472     Vdbe *v,          /* Generate code into this VM */
   473    473     int iOffset,      /* Register holding the offset counter */
   474    474     int iContinue     /* Jump here to skip the current record */
   475    475   ){
   476    476     if( iOffset>0 && iContinue!=0 ){
   477    477       int addr;
   478    478       sqlite3VdbeAddOp2(v, OP_AddImm, iOffset, -1);
   479         -    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, iOffset);
          479  +    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, iOffset); VdbeCoverage(v);
   480    480       sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
   481    481       VdbeComment((v, "skip OFFSET records"));
   482    482       sqlite3VdbeJumpHere(v, addr);
   483    483     }
   484    484   }
   485    485   
   486    486   /*
................................................................................
   500    500     int iMem           /* First element */
   501    501   ){
   502    502     Vdbe *v;
   503    503     int r1;
   504    504   
   505    505     v = pParse->pVdbe;
   506    506     r1 = sqlite3GetTempReg(pParse);
   507         -  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
          507  +  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
   508    508     sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
   509    509     sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
   510    510     sqlite3ReleaseTempReg(pParse, r1);
   511    511   }
   512    512   
   513    513   #ifndef SQLITE_OMIT_SUBQUERY
   514    514   /*
................................................................................
   581    581     if( pOrderBy==0 && !hasDistinct ){
   582    582       codeOffset(v, p->iOffset, iContinue);
   583    583     }
   584    584   
   585    585     /* Pull the requested columns.
   586    586     */
   587    587     nResultCol = pEList->nExpr;
          588  +
   588    589     if( pDest->iSdst==0 ){
   589    590       pDest->iSdst = pParse->nMem+1;
   590         -    pDest->nSdst = nResultCol;
          591  +    pParse->nMem += nResultCol;
          592  +  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
          593  +    /* This is an error condition that can result, for example, when a SELECT
          594  +    ** on the right-hand side of an INSERT contains more result columns than
          595  +    ** there are columns in the table on the left.  The error will be caught
          596  +    ** and reported later.  But we need to make sure enough memory is allocated
          597  +    ** to avoid other spurious errors in the meantime. */
   591    598       pParse->nMem += nResultCol;
   592         -  }else{ 
   593         -    assert( pDest->nSdst==nResultCol );
   594    599     }
          600  +  pDest->nSdst = nResultCol;
   595    601     regResult = pDest->iSdst;
   596    602     if( srcTab>=0 ){
   597    603       for(i=0; i<nResultCol; i++){
   598    604         sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
   599    605         VdbeComment((v, "%s", pEList->a[i].zName));
   600    606       }
   601    607     }else if( eDest!=SRT_Exists ){
   602    608       /* If the destination is an EXISTS(...) expression, the actual
   603    609       ** values returned by the SELECT are not required.
   604    610       */
   605    611       sqlite3ExprCodeExprList(pParse, pEList, regResult,
   606         -                            (eDest==SRT_Output)?SQLITE_ECEL_DUP:0);
          612  +                  (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
   607    613     }
   608    614   
   609    615     /* If the DISTINCT keyword was present on the SELECT statement
   610    616     ** and this row has been seen before, then do not make this row
   611    617     ** part of the result.
   612    618     */
   613    619     if( hasDistinct ){
................................................................................
   634    640           pOp->p2 = regPrev;
   635    641   
   636    642           iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
   637    643           for(i=0; i<nResultCol; i++){
   638    644             CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
   639    645             if( i<nResultCol-1 ){
   640    646               sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
          647  +            VdbeCoverage(v);
   641    648             }else{
   642    649               sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
   643         -          }
          650  +            VdbeCoverage(v);
          651  +           }
   644    652             sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
   645    653             sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
   646    654           }
   647    655           assert( sqlite3VdbeCurrentAddr(v)==iJump );
   648    656           sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
   649    657           break;
   650    658         }
................................................................................
   702    710         if( eDest==SRT_DistTable ){
   703    711           /* If the destination is DistTable, then cursor (iParm+1) is open
   704    712           ** on an ephemeral index. If the current row is already present
   705    713           ** in the index, do not write it to the output. If not, add the
   706    714           ** current row to the index and proceed with writing it to the
   707    715           ** output table as well.  */
   708    716           int addr = sqlite3VdbeCurrentAddr(v) + 4;
   709         -        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
          717  +        sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
   710    718           sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
   711    719           assert( pOrderBy==0 );
   712    720         }
   713    721   #endif
   714    722         if( pOrderBy ){
   715    723           pushOntoSorter(pParse, pOrderBy, p, r1);
   716    724         }else{
................................................................................
   806    814         ExprList *pSO;
   807    815         pSO = pDest->pOrderBy;
   808    816         assert( pSO );
   809    817         nKey = pSO->nExpr;
   810    818         r1 = sqlite3GetTempReg(pParse);
   811    819         r2 = sqlite3GetTempRange(pParse, nKey+2);
   812    820         r3 = r2+nKey+1;
   813         -      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
   814    821         if( eDest==SRT_DistQueue ){
   815    822           /* If the destination is DistQueue, then cursor (iParm+1) is open
   816    823           ** on a second ephemeral index that holds all values every previously
   817         -        ** added to the queue.  Only add this new value if it has never before
   818         -        ** been added */
   819         -        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, r3, 0);
          824  +        ** added to the queue. */
          825  +        addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 
          826  +                                        regResult, nResultCol);
          827  +        VdbeCoverage(v);
          828  +      }
          829  +      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
          830  +      if( eDest==SRT_DistQueue ){
   820    831           sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
   821    832           sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
   822    833         }
   823    834         for(i=0; i<nKey; i++){
   824    835           sqlite3VdbeAddOp2(v, OP_SCopy,
   825    836                             regResult + pSO->a[i].u.x.iOrderByCol - 1,
   826    837                             r2+i);
................................................................................
   851    862     }
   852    863   
   853    864     /* Jump to the end of the loop if the LIMIT is reached.  Except, if
   854    865     ** there is a sorter, in which case the sorter has already limited
   855    866     ** the output for us.
   856    867     */
   857    868     if( pOrderBy==0 && p->iLimit ){
   858         -    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
          869  +    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
   859    870     }
   860    871   }
   861    872   
   862    873   /*
   863    874   ** Allocate a KeyInfo object sufficient for an index of N key columns and
   864    875   ** X extra columns.
   865    876   */
................................................................................
  1070   1081       regRowid = sqlite3GetTempReg(pParse);
  1071   1082     }
  1072   1083     if( p->selFlags & SF_UseSorter ){
  1073   1084       int regSortOut = ++pParse->nMem;
  1074   1085       int ptab2 = pParse->nTab++;
  1075   1086       sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  1076   1087       addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
         1088  +    VdbeCoverage(v);
  1077   1089       codeOffset(v, p->iOffset, addrContinue);
  1078   1090       sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  1079   1091       sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  1080   1092       sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  1081   1093     }else{
  1082         -    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
         1094  +    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  1083   1095       codeOffset(v, p->iOffset, addrContinue);
  1084   1096       sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  1085   1097     }
  1086   1098     switch( eDest ){
  1087   1099       case SRT_Table:
  1088   1100       case SRT_EphemTab: {
  1089   1101         testcase( eDest==SRT_Table );
................................................................................
  1133   1145     sqlite3ReleaseTempReg(pParse, regRow);
  1134   1146     sqlite3ReleaseTempReg(pParse, regRowid);
  1135   1147   
  1136   1148     /* The bottom of the loop
  1137   1149     */
  1138   1150     sqlite3VdbeResolveLabel(v, addrContinue);
  1139   1151     if( p->selFlags & SF_UseSorter ){
  1140         -    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
         1152  +    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  1141   1153     }else{
  1142         -    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
         1154  +    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  1143   1155     }
  1144   1156     sqlite3VdbeResolveLabel(v, addrBreak);
  1145   1157     if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  1146   1158       sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  1147   1159     }
  1148   1160   }
  1149   1161   
................................................................................
  1683   1695         if( n==0 ){
  1684   1696           sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  1685   1697         }else if( n>=0 && p->nSelectRow>(u64)n ){
  1686   1698           p->nSelectRow = n;
  1687   1699         }
  1688   1700       }else{
  1689   1701         sqlite3ExprCode(pParse, p->pLimit, iLimit);
  1690         -      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
         1702  +      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  1691   1703         VdbeComment((v, "LIMIT counter"));
  1692         -      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
         1704  +      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
  1693   1705       }
  1694   1706       if( p->pOffset ){
  1695   1707         p->iOffset = iOffset = ++pParse->nMem;
  1696   1708         pParse->nMem++;   /* Allocate an extra register for limit+offset */
  1697   1709         sqlite3ExprCode(pParse, p->pOffset, iOffset);
  1698         -      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
         1710  +      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  1699   1711         VdbeComment((v, "OFFSET counter"));
  1700         -      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
         1712  +      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
  1701   1713         sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  1702   1714         sqlite3VdbeJumpHere(v, addr1);
  1703   1715         sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  1704   1716         VdbeComment((v, "LIMIT+OFFSET"));
  1705         -      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
         1717  +      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
  1706   1718         sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  1707   1719         sqlite3VdbeJumpHere(v, addr1);
  1708   1720       }
  1709   1721     }
  1710   1722   }
  1711   1723   
  1712   1724   #ifndef SQLITE_OMIT_COMPOUND_SELECT
................................................................................
  1887   1899     /* Store the results of the setup-query in Queue. */
  1888   1900     pSetup->pNext = 0;
  1889   1901     rc = sqlite3Select(pParse, pSetup, &destQueue);
  1890   1902     pSetup->pNext = p;
  1891   1903     if( rc ) goto end_of_recursive_query;
  1892   1904   
  1893   1905     /* Find the next row in the Queue and output that row */
  1894         -  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak);
         1906  +  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  1895   1907   
  1896   1908     /* Transfer the next row in Queue over to Current */
  1897   1909     sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  1898   1910     if( pOrderBy ){
  1899   1911       sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  1900   1912     }else{
  1901   1913       sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
................................................................................
  1903   1915     sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  1904   1916   
  1905   1917     /* Output the single row in Current */
  1906   1918     addrCont = sqlite3VdbeMakeLabel(v);
  1907   1919     codeOffset(v, regOffset, addrCont);
  1908   1920     selectInnerLoop(pParse, p, p->pEList, iCurrent,
  1909   1921         0, 0, pDest, addrCont, addrBreak);
  1910         -  if( regLimit ) sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
         1922  +  if( regLimit ){
         1923  +    sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
         1924  +    VdbeCoverage(v);
         1925  +  }
  1911   1926     sqlite3VdbeResolveLabel(v, addrCont);
  1912   1927   
  1913   1928     /* Execute the recursive SELECT taking the single row in Current as
  1914   1929     ** the value for the recursive-table. Store the results in the Queue.
  1915   1930     */
  1916   1931     p->pPrior = 0;
  1917   1932     sqlite3Select(pParse, p, &destQueue);
................................................................................
  2063   2078         if( rc ){
  2064   2079           goto multi_select_end;
  2065   2080         }
  2066   2081         p->pPrior = 0;
  2067   2082         p->iLimit = pPrior->iLimit;
  2068   2083         p->iOffset = pPrior->iOffset;
  2069   2084         if( p->iLimit ){
  2070         -        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
         2085  +        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
  2071   2086           VdbeComment((v, "Jump ahead if LIMIT reached"));
  2072   2087         }
  2073   2088         explainSetInteger(iSub2, pParse->iNextSelectId);
  2074   2089         rc = sqlite3Select(pParse, p, &dest);
  2075   2090         testcase( rc!=SQLITE_OK );
  2076   2091         pDelete = p->pPrior;
  2077   2092         p->pPrior = pPrior;
................................................................................
  2170   2185             Select *pFirst = p;
  2171   2186             while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  2172   2187             generateColumnNames(pParse, 0, pFirst->pEList);
  2173   2188           }
  2174   2189           iBreak = sqlite3VdbeMakeLabel(v);
  2175   2190           iCont = sqlite3VdbeMakeLabel(v);
  2176   2191           computeLimitRegisters(pParse, p, iBreak);
  2177         -        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
         2192  +        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  2178   2193           iStart = sqlite3VdbeCurrentAddr(v);
  2179   2194           selectInnerLoop(pParse, p, p->pEList, unionTab,
  2180   2195                           0, 0, &dest, iCont, iBreak);
  2181   2196           sqlite3VdbeResolveLabel(v, iCont);
  2182         -        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
         2197  +        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  2183   2198           sqlite3VdbeResolveLabel(v, iBreak);
  2184   2199           sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  2185   2200         }
  2186   2201         break;
  2187   2202       }
  2188   2203       default: assert( p->op==TK_INTERSECT ); {
  2189   2204         int tab1, tab2;
................................................................................
  2245   2260           Select *pFirst = p;
  2246   2261           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  2247   2262           generateColumnNames(pParse, 0, pFirst->pEList);
  2248   2263         }
  2249   2264         iBreak = sqlite3VdbeMakeLabel(v);
  2250   2265         iCont = sqlite3VdbeMakeLabel(v);
  2251   2266         computeLimitRegisters(pParse, p, iBreak);
  2252         -      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
         2267  +      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  2253   2268         r1 = sqlite3GetTempReg(pParse);
  2254   2269         iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  2255         -      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
         2270  +      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  2256   2271         sqlite3ReleaseTempReg(pParse, r1);
  2257   2272         selectInnerLoop(pParse, p, p->pEList, tab1,
  2258   2273                         0, 0, &dest, iCont, iBreak);
  2259   2274         sqlite3VdbeResolveLabel(v, iCont);
  2260         -      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
         2275  +      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  2261   2276         sqlite3VdbeResolveLabel(v, iBreak);
  2262   2277         sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  2263   2278         sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  2264   2279         break;
  2265   2280       }
  2266   2281     }
  2267   2282   
................................................................................
  2360   2375     addr = sqlite3VdbeCurrentAddr(v);
  2361   2376     iContinue = sqlite3VdbeMakeLabel(v);
  2362   2377   
  2363   2378     /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
  2364   2379     */
  2365   2380     if( regPrev ){
  2366   2381       int j1, j2;
  2367         -    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
         2382  +    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  2368   2383       j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  2369   2384                                 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  2370         -    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
         2385  +    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
  2371   2386       sqlite3VdbeJumpHere(v, j1);
  2372   2387       sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  2373   2388       sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  2374   2389     }
  2375   2390     if( pParse->db->mallocFailed ) return 0;
  2376   2391   
  2377   2392     /* Suppress the first OFFSET entries if there is an OFFSET clause
................................................................................
  2464   2479         break;
  2465   2480       }
  2466   2481     }
  2467   2482   
  2468   2483     /* Jump to the end of the loop if the LIMIT is reached.
  2469   2484     */
  2470   2485     if( p->iLimit ){
  2471         -    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
         2486  +    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
  2472   2487     }
  2473   2488   
  2474   2489     /* Generate the subroutine return
  2475   2490     */
  2476   2491     sqlite3VdbeResolveLabel(v, iContinue);
  2477   2492     sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  2478   2493   
................................................................................
  2780   2795     */
  2781   2796     if( op==TK_EXCEPT || op==TK_INTERSECT ){
  2782   2797       addrEofA_noB = addrEofA = labelEnd;
  2783   2798     }else{  
  2784   2799       VdbeNoopComment((v, "eof-A subroutine"));
  2785   2800       addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  2786   2801       addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
         2802  +                                     VdbeCoverage(v);
  2787   2803       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  2788   2804       p->nSelectRow += pPrior->nSelectRow;
  2789   2805     }
  2790   2806   
  2791   2807     /* Generate a subroutine to run when the results from select B
  2792   2808     ** are exhausted and only data in select A remains.
  2793   2809     */
  2794   2810     if( op==TK_INTERSECT ){
  2795   2811       addrEofB = addrEofA;
  2796   2812       if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  2797   2813     }else{  
  2798   2814       VdbeNoopComment((v, "eof-B subroutine"));
  2799   2815       addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  2800         -    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd);
         2816  +    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  2801   2817       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  2802   2818     }
  2803   2819   
  2804   2820     /* Generate code to handle the case of A<B
  2805   2821     */
  2806   2822     VdbeNoopComment((v, "A-lt-B subroutine"));
  2807   2823     addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  2808         -  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA);
         2824  +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  2809   2825     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  2810   2826   
  2811   2827     /* Generate code to handle the case of A==B
  2812   2828     */
  2813   2829     if( op==TK_ALL ){
  2814   2830       addrAeqB = addrAltB;
  2815   2831     }else if( op==TK_INTERSECT ){
  2816   2832       addrAeqB = addrAltB;
  2817   2833       addrAltB++;
  2818   2834     }else{
  2819   2835       VdbeNoopComment((v, "A-eq-B subroutine"));
  2820   2836       addrAeqB =
  2821         -    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA);
         2837  +    sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  2822   2838       sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  2823   2839     }
  2824   2840   
  2825   2841     /* Generate code to handle the case of A>B
  2826   2842     */
  2827   2843     VdbeNoopComment((v, "A-gt-B subroutine"));
  2828   2844     addrAgtB = sqlite3VdbeCurrentAddr(v);
  2829   2845     if( op==TK_ALL || op==TK_UNION ){
  2830   2846       sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  2831   2847     }
  2832         -  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB);
         2848  +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  2833   2849     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  2834   2850   
  2835   2851     /* This code runs once to initialize everything.
  2836   2852     */
  2837   2853     sqlite3VdbeJumpHere(v, j1);
  2838         -  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB);
  2839         -  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB);
         2854  +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
         2855  +  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  2840   2856   
  2841   2857     /* Implement the main merge loop
  2842   2858     */
  2843   2859     sqlite3VdbeResolveLabel(v, labelCmpr);
  2844   2860     sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  2845   2861     sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  2846   2862                            (char*)pKeyMerge, P4_KEYINFO);
  2847   2863     sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  2848         -  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
         2864  +  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  2849   2865   
  2850   2866     /* Jump to the this point in order to terminate the query.
  2851   2867     */
  2852   2868     sqlite3VdbeResolveLabel(v, labelEnd);
  2853   2869   
  2854   2870     /* Set the number of output columns
  2855   2871     */
................................................................................
  4381   4397     ** may have been used, invalidating the underlying buffer holding the
  4382   4398     ** text or blob value. See ticket [883034dcb5].
  4383   4399     **
  4384   4400     ** Another solution would be to change the OP_SCopy used to copy cached
  4385   4401     ** values to an OP_Copy.
  4386   4402     */
  4387   4403     if( regHit ){
  4388         -    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
         4404  +    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  4389   4405     }
  4390   4406     sqlite3ExprCacheClear(pParse);
  4391   4407     for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  4392   4408       sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  4393   4409     }
  4394   4410     pAggInfo->directMode = 0;
  4395   4411     sqlite3ExprCacheClear(pParse);
................................................................................
  4577   4593         pItem->regReturn = ++pParse->nMem;
  4578   4594         topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  4579   4595         pItem->addrFillSub = topAddr+1;
  4580   4596         if( pItem->isCorrelated==0 ){
  4581   4597           /* If the subquery is not correlated and if we are not inside of
  4582   4598           ** a trigger, then we only need to compute the value of the subquery
  4583   4599           ** once. */
  4584         -        onceAddr = sqlite3CodeOnce(pParse);
         4600  +        onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  4585   4601           VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  4586   4602         }else{
  4587   4603           VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  4588   4604         }
  4589   4605         sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  4590   4606         explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  4591   4607         sqlite3Select(pParse, pSub, &dest);
................................................................................
  4915   4931           sqlite3ReleaseTempReg(pParse, regRecord);
  4916   4932           sqlite3ReleaseTempRange(pParse, regBase, nCol);
  4917   4933           sqlite3WhereEnd(pWInfo);
  4918   4934           sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  4919   4935           sortOut = sqlite3GetTempReg(pParse);
  4920   4936           sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  4921   4937           sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  4922         -        VdbeComment((v, "GROUP BY sort"));
         4938  +        VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  4923   4939           sAggInfo.useSortingIdx = 1;
  4924   4940           sqlite3ExprCacheClear(pParse);
  4925   4941         }
  4926   4942   
  4927   4943         /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  4928   4944         ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  4929   4945         ** Then compare the current GROUP BY terms against the GROUP BY terms
................................................................................
  4942   4958             sAggInfo.directMode = 1;
  4943   4959             sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  4944   4960           }
  4945   4961         }
  4946   4962         sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  4947   4963                             (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  4948   4964         j1 = sqlite3VdbeCurrentAddr(v);
  4949         -      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
         4965  +      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
  4950   4966   
  4951   4967         /* Generate code that runs whenever the GROUP BY changes.
  4952   4968         ** Changes in the GROUP BY are detected by the previous code
  4953   4969         ** block.  If there were no changes, this block is skipped.
  4954   4970         **
  4955   4971         ** This code copies current group by terms in b0,b1,b2,...
  4956   4972         ** over to a0,a1,a2.  It then calls the output subroutine
  4957   4973         ** and resets the aggregate accumulator registers in preparation
  4958   4974         ** for the next GROUP BY batch.
  4959   4975         */
  4960   4976         sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  4961   4977         sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  4962   4978         VdbeComment((v, "output one row"));
  4963         -      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
         4979  +      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  4964   4980         VdbeComment((v, "check abort flag"));
  4965   4981         sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  4966   4982         VdbeComment((v, "reset accumulator"));
  4967   4983   
  4968   4984         /* Update the aggregate accumulators based on the content of
  4969   4985         ** the current row
  4970   4986         */
................................................................................
  4973   4989         sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  4974   4990         VdbeComment((v, "indicate data in accumulator"));
  4975   4991   
  4976   4992         /* End of the loop
  4977   4993         */
  4978   4994         if( groupBySort ){
  4979   4995           sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
         4996  +        VdbeCoverage(v);
  4980   4997         }else{
  4981   4998           sqlite3WhereEnd(pWInfo);
  4982   4999           sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  4983   5000         }
  4984   5001   
  4985   5002         /* Output the final row of result
  4986   5003         */
................................................................................
  5000   5017         */
  5001   5018         addrSetAbort = sqlite3VdbeCurrentAddr(v);
  5002   5019         sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  5003   5020         VdbeComment((v, "set abort flag"));
  5004   5021         sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  5005   5022         sqlite3VdbeResolveLabel(v, addrOutputRow);
  5006   5023         addrOutputRow = sqlite3VdbeCurrentAddr(v);
  5007         -      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
         5024  +      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
  5008   5025         VdbeComment((v, "Groupby result generator entry point"));
  5009   5026         sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  5010   5027         finalizeAggFunctions(pParse, &sAggInfo);
  5011   5028         sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  5012   5029         selectInnerLoop(pParse, p, p->pEList, -1, pOrderBy,
  5013   5030                         &sDistinct, pDest,
  5014   5031                         addrOutputRow+1, addrSetAbort);

Changes to src/shell.c.

    61     61   # define write_history(X)
    62     62   # define stifle_history(X)
    63     63   #endif
    64     64   
    65     65   #if defined(_WIN32) || defined(WIN32)
    66     66   # include <io.h>
    67     67   #define isatty(h) _isatty(h)
    68         -#define access(f,m) _access((f),(m))
           68  +#ifndef access
           69  +# define access(f,m) _access((f),(m))
           70  +#endif
    69     71   #undef popen
    70     72   #define popen _popen
    71     73   #undef pclose
    72     74   #define pclose _pclose
    73     75   #else
    74     76   /* Make sure isatty() has a prototype.
    75     77   */
................................................................................
   440    442   ** An pointer to an instance of this structure is passed from
   441    443   ** the main program to the callback.  This is used to communicate
   442    444   ** state and mode information.
   443    445   */
   444    446   struct callback_data {
   445    447     sqlite3 *db;           /* The database */
   446    448     int echoOn;            /* True to echo input commands */
          449  +  int autoEQP;           /* Run EXPLAIN QUERY PLAN prior to seach SQL statement */
   447    450     int statsOn;           /* True to display memory stats before each finalize */
   448    451     int cnt;               /* Number of records displayed so far */
   449    452     FILE *out;             /* Write results here */
   450    453     FILE *traceOut;        /* Output for sqlite3_trace() */
   451    454     int nErr;              /* Number of errors seen */
   452    455     int mode;              /* An output mode setting */
   453    456     int writableSchema;    /* True if PRAGMA writable_schema=ON */
................................................................................
  1004   1007     const char *zFirstRow    /* Print before first row, if not NULL */
  1005   1008   ){
  1006   1009     sqlite3_stmt *pSelect;
  1007   1010     int rc;
  1008   1011     int nResult;
  1009   1012     int i;
  1010   1013     const char *z;
  1011         -  rc = sqlite3_prepare(p->db, zSelect, -1, &pSelect, 0);
         1014  +  rc = sqlite3_prepare_v2(p->db, zSelect, -1, &pSelect, 0);
  1012   1015     if( rc!=SQLITE_OK || !pSelect ){
  1013   1016       fprintf(p->out, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db));
  1014   1017       if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++;
  1015   1018       return rc;
  1016   1019     }
  1017   1020     rc = sqlite3_step(pSelect);
  1018   1021     nResult = sqlite3_column_count(pSelect);
................................................................................
  1295   1298         }
  1296   1299   
  1297   1300         /* echo the sql statement if echo on */
  1298   1301         if( pArg && pArg->echoOn ){
  1299   1302           const char *zStmtSql = sqlite3_sql(pStmt);
  1300   1303           fprintf(pArg->out, "%s\n", zStmtSql ? zStmtSql : zSql);
  1301   1304         }
         1305  +
         1306  +      /* Show the EXPLAIN QUERY PLAN if .eqp is on */
         1307  +      if( pArg && pArg->autoEQP ){
         1308  +        sqlite3_stmt *pExplain;
         1309  +        char *zEQP = sqlite3_mprintf("EXPLAIN QUERY PLAN %s", sqlite3_sql(pStmt));
         1310  +        rc = sqlite3_prepare_v2(db, zEQP, -1, &pExplain, 0);
         1311  +        if( rc==SQLITE_OK ){
         1312  +          while( sqlite3_step(pExplain)==SQLITE_ROW ){
         1313  +            fprintf(pArg->out,"--EQP-- %d,", sqlite3_column_int(pExplain, 0));
         1314  +            fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 1));
         1315  +            fprintf(pArg->out,"%d,", sqlite3_column_int(pExplain, 2));
         1316  +            fprintf(pArg->out,"%s\n", sqlite3_column_text(pExplain, 3));
         1317  +          }
         1318  +        }
         1319  +        sqlite3_finalize(pExplain);
         1320  +        sqlite3_free(zEQP);
         1321  +      }
  1302   1322   
  1303   1323         /* Output TESTCTRL_EXPLAIN text of requested */
  1304   1324         if( pArg && pArg->mode==MODE_Explain ){
  1305   1325           const char *zExplain = 0;
  1306   1326           sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT, pStmt, &zExplain);
  1307   1327           if( zExplain && zExplain[0] ){
  1308   1328             fprintf(pArg->out, "%s", zExplain);
................................................................................
  1452   1472       char *zTmp = 0;
  1453   1473       int nRow = 0;
  1454   1474      
  1455   1475       zTableInfo = appendText(zTableInfo, "PRAGMA table_info(", 0);
  1456   1476       zTableInfo = appendText(zTableInfo, zTable, '"');
  1457   1477       zTableInfo = appendText(zTableInfo, ");", 0);
  1458   1478   
  1459         -    rc = sqlite3_prepare(p->db, zTableInfo, -1, &pTableInfo, 0);
         1479  +    rc = sqlite3_prepare_v2(p->db, zTableInfo, -1, &pTableInfo, 0);
  1460   1480       free(zTableInfo);
  1461   1481       if( rc!=SQLITE_OK || !pTableInfo ){
  1462   1482         return 1;
  1463   1483       }
  1464   1484   
  1465   1485       zSelect = appendText(zSelect, "SELECT 'INSERT INTO ' || ", 0);
  1466   1486       /* Always quote the table name, even if it appears to be pure ascii,
................................................................................
  1889   1909     }else{
  1890   1910       while( c!=EOF && c!=cSep && c!='\n' ){
  1891   1911         csv_append_char(p, c);
  1892   1912         c = fgetc(p->in);
  1893   1913       }
  1894   1914       if( c=='\n' ){
  1895   1915         p->nLine++;
  1896         -      if( p->n>1 && p->z[p->n-1]=='\r' ) p->n--;
         1916  +      if( p->n>0 && p->z[p->n-1]=='\r' ) p->n--;
  1897   1917       }
  1898   1918       p->cTerm = c;
  1899   1919     }
  1900   1920     if( p->z ) p->z[p->n] = 0;
  1901   1921     return p->z;
  1902   1922   }
  1903   1923   
................................................................................
  2294   2314       sqlite3_exec(p->db, "RELEASE dump;", 0, 0, 0);
  2295   2315       fprintf(p->out, p->nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n");
  2296   2316     }else
  2297   2317   
  2298   2318     if( c=='e' && strncmp(azArg[0], "echo", n)==0 && nArg>1 && nArg<3 ){
  2299   2319       p->echoOn = booleanValue(azArg[1]);
  2300   2320     }else
         2321  +
         2322  +  if( c=='e' && strncmp(azArg[0], "eqp", n)==0 && nArg>1 && nArg<3 ){
         2323  +    p->autoEQP = booleanValue(azArg[1]);
         2324  +  }else
  2301   2325   
  2302   2326     if( c=='e' && strncmp(azArg[0], "exit", n)==0 ){
  2303   2327       if( nArg>1 && (rc = (int)integerValue(azArg[1]))!=0 ) exit(rc);
  2304   2328       rc = 2;
  2305   2329     }else
  2306   2330   
  2307   2331     if( c=='e' && strncmp(azArg[0], "explain", n)==0 && nArg<3 ){
................................................................................
  2395   2419       zSql = sqlite3_mprintf("SELECT * FROM %s", zTable);
  2396   2420       if( zSql==0 ){
  2397   2421         fprintf(stderr, "Error: out of memory\n");
  2398   2422         xCloser(sCsv.in);
  2399   2423         return 1;
  2400   2424       }
  2401   2425       nByte = strlen30(zSql);
  2402         -    rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
         2426  +    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2403   2427       if( rc && sqlite3_strglob("no such table: *", sqlite3_errmsg(db))==0 ){
  2404   2428         char *zCreate = sqlite3_mprintf("CREATE TABLE %s", zTable);
  2405   2429         char cSep = '(';
  2406   2430         while( csv_read_one_field(&sCsv) ){
  2407   2431           zCreate = sqlite3_mprintf("%z%c\n  \"%s\" TEXT", zCreate, cSep, sCsv.z);
  2408   2432           cSep = ',';
  2409   2433           if( sCsv.cTerm!=sCsv.cSeparator ) break;
................................................................................
  2421   2445         if( rc ){
  2422   2446           fprintf(stderr, "CREATE TABLE %s(...) failed: %s\n", zTable,
  2423   2447                   sqlite3_errmsg(db));
  2424   2448           sqlite3_free(sCsv.z);
  2425   2449           xCloser(sCsv.in);
  2426   2450           return 1;
  2427   2451         }
  2428         -      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
         2452  +      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2429   2453       }
  2430   2454       sqlite3_free(zSql);
  2431   2455       if( rc ){
  2432   2456         if (pStmt) sqlite3_finalize(pStmt);
  2433   2457         fprintf(stderr,"Error: %s\n", sqlite3_errmsg(db));
  2434   2458         xCloser(sCsv.in);
  2435   2459         return 1;
................................................................................
  2448   2472       j = strlen30(zSql);
  2449   2473       for(i=1; i<nCol; i++){
  2450   2474         zSql[j++] = ',';
  2451   2475         zSql[j++] = '?';
  2452   2476       }
  2453   2477       zSql[j++] = ')';
  2454   2478       zSql[j] = 0;
  2455         -    rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
         2479  +    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  2456   2480       sqlite3_free(zSql);
  2457   2481       if( rc ){
  2458   2482         fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
  2459   2483         if (pStmt) sqlite3_finalize(pStmt);
  2460   2484         xCloser(sCsv.in);
  2461   2485         return 1;
  2462   2486       }
................................................................................
  2867   2891       sqlite3_snprintf(sizeof(p->separator), p->separator,
  2868   2892                        "%.*s", (int)sizeof(p->separator)-1, azArg[1]);
  2869   2893     }else
  2870   2894   
  2871   2895     if( c=='s' && strncmp(azArg[0], "show", n)==0 && nArg==1 ){
  2872   2896       int i;
  2873   2897       fprintf(p->out,"%9.9s: %s\n","echo", p->echoOn ? "on" : "off");
         2898  +    fprintf(p->out,"%9.9s: %s\n","eqp", p->autoEQP ? "on" : "off");
  2874   2899       fprintf(p->out,"%9.9s: %s\n","explain", p->explainPrev.valid ? "on" :"off");
  2875   2900       fprintf(p->out,"%9.9s: %s\n","headers", p->showHeader ? "on" : "off");
  2876   2901       fprintf(p->out,"%9.9s: %s\n","mode", modeDescr[p->mode]);
  2877   2902       fprintf(p->out,"%9.9s: ", "nullvalue");
  2878   2903         output_c_string(p->out, p->nullvalue);
  2879   2904         fprintf(p->out, "\n");
  2880   2905       fprintf(p->out,"%9.9s: %s\n","output",
................................................................................
  3544   3569     struct callback_data data;
  3545   3570     const char *zInitFile = 0;
  3546   3571     char *zFirstCmd = 0;
  3547   3572     int i;
  3548   3573     int rc = 0;
  3549   3574     int warnInmemoryDb = 0;
  3550   3575   
         3576  +#if USE_SYSTEM_SQLITE+0!=1
  3551   3577     if( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)!=0 ){
  3552   3578       fprintf(stderr, "SQLite header and source version mismatch\n%s\n%s\n",
  3553   3579               sqlite3_sourceid(), SQLITE_SOURCE_ID);
  3554   3580       exit(1);
  3555   3581     }
         3582  +#endif
  3556   3583     Argv0 = argv[0];
  3557   3584     main_init(&data);
  3558   3585     stdin_is_interactive = isatty(0);
  3559   3586   
  3560   3587     /* Make sure we have a valid signal handler early, before anything
  3561   3588     ** else is done.
  3562   3589     */
................................................................................
  3642   3669   #ifndef SQLITE_OMIT_MEMORYDB
  3643   3670       data.zDbFilename = ":memory:";
  3644   3671       warnInmemoryDb = argc==1;
  3645   3672   #else
  3646   3673       fprintf(stderr,"%s: Error: no database filename specified\n", Argv0);
  3647   3674       return 1;
  3648   3675   #endif
         3676  +#ifdef SQLITE_SHELL_DBNAME_PROC
         3677  +    { extern void SQLITE_SHELL_DBNAME_PROC(const char**);
         3678  +      SQLITE_SHELL_DBNAME_PROC(&data.zDbFilename);
         3679  +      warnInmemoryDb = 0; }
         3680  +#endif
  3649   3681     }
  3650   3682     data.out = stdout;
  3651   3683   
  3652   3684     /* Go ahead and open the database file if it already exists.  If the
  3653   3685     ** file does not exist, delay opening it.  This prevents empty database
  3654   3686     ** files from being created if a user mistypes the database name argument
  3655   3687     ** to the sqlite command-line tool.
................................................................................
  3697   3729                          "%s",cmdline_option_value(argc,argv,++i));
  3698   3730       }else if( strcmp(z,"-header")==0 ){
  3699   3731         data.showHeader = 1;
  3700   3732       }else if( strcmp(z,"-noheader")==0 ){
  3701   3733         data.showHeader = 0;
  3702   3734       }else if( strcmp(z,"-echo")==0 ){
  3703   3735         data.echoOn = 1;
         3736  +    }else if( strcmp(z,"-eqp")==0 ){
         3737  +      data.autoEQP = 1;
  3704   3738       }else if( strcmp(z,"-stats")==0 ){
  3705   3739         data.statsOn = 1;
  3706   3740       }else if( strcmp(z,"-bail")==0 ){
  3707   3741         bail_on_error = 1;
  3708   3742       }else if( strcmp(z,"-version")==0 ){
  3709   3743         printf("%s %s\n", sqlite3_libversion(), sqlite3_sourceid());
  3710   3744         return 0;

Changes to src/sqlite.h.in.

  6113   6113   #define SQLITE_TESTCTRL_RESERVE                 14
  6114   6114   #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
  6115   6115   #define SQLITE_TESTCTRL_ISKEYWORD               16
  6116   6116   #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
  6117   6117   #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
  6118   6118   #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
  6119   6119   #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
  6120         -#define SQLITE_TESTCTRL_LAST                    20
         6120  +#define SQLITE_TESTCTRL_VDBE_COVERAGE           21
         6121  +#define SQLITE_TESTCTRL_LAST                    21
  6121   6122   
  6122   6123   /*
  6123   6124   ** CAPI3REF: SQLite Runtime Status
  6124   6125   **
  6125   6126   ** ^This interface is used to retrieve runtime status information
  6126   6127   ** about the performance of SQLite, and optionally to reset various
  6127   6128   ** highwater marks.  ^The first argument is an integer code for

Changes to src/sqliteInt.h.

     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   ** Internal interface definitions for SQLite.
    13     13   **
    14     14   */
    15         -#include "sqlite3.h"
    16     15   #ifndef _SQLITEINT_H_
    17     16   #define _SQLITEINT_H_
    18     17   
    19     18   /*
    20     19   ** These #defines should enable >2GB file support on POSIX if the
    21     20   ** underlying operating system supports it.  If the OS lacks
    22     21   ** large file support, or if the OS is windows, these should be no-ops.
................................................................................
    43     42   #ifndef SQLITE_DISABLE_LFS
    44     43   # define _LARGE_FILE       1
    45     44   # ifndef _FILE_OFFSET_BITS
    46     45   #   define _FILE_OFFSET_BITS 64
    47     46   # endif
    48     47   # define _LARGEFILE_SOURCE 1
    49     48   #endif
           49  +
           50  +/* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
           51  +** first in QNX.
           52  +*/
           53  +#include "sqlite3.h"
    50     54   
    51     55   /*
    52     56   ** Include the configuration header output by 'configure' if we're using the
    53     57   ** autoconf-based build
    54     58   */
    55     59   #ifdef _HAVE_SQLITE_CONFIG_H
    56     60   #include "config.h"
................................................................................
  1318   1322   ** affinity value. 
  1319   1323   */
  1320   1324   #define SQLITE_AFF_MASK     0x67
  1321   1325   
  1322   1326   /*
  1323   1327   ** Additional bit values that can be ORed with an affinity without
  1324   1328   ** changing the affinity.
         1329  +**
         1330  +** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
         1331  +** It causes an assert() to fire if either operand to a comparison
         1332  +** operator is NULL.  It is added to certain comparison operators to
         1333  +** prove that the operands are always NOT NULL.
  1325   1334   */
  1326   1335   #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
  1327   1336   #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
  1328   1337   #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
         1338  +#define SQLITE_NOTNULL      0x88  /* Assert that operands are never NULL */
  1329   1339   
  1330   1340   /*
  1331   1341   ** An object of this type is created for each virtual table present in
  1332   1342   ** the database schema. 
  1333   1343   **
  1334   1344   ** If the database schema is shared, then there is one instance of this
  1335   1345   ** structure for each database connection (sqlite3*) that uses the shared
................................................................................
  1580   1590   ** Records are used to store the content of a table row and to store
  1581   1591   ** the key of an index.  A blob encoding of a record is created by
  1582   1592   ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  1583   1593   ** OP_Column opcode.
  1584   1594   **
  1585   1595   ** This structure holds a record that has already been disassembled
  1586   1596   ** into its constituent fields.
         1597  +**
         1598  +** The r1 and r2 member variables are only used by the optimized comparison
         1599  +** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
  1587   1600   */
  1588   1601   struct UnpackedRecord {
  1589   1602     KeyInfo *pKeyInfo;  /* Collation and sort-order information */
  1590   1603     u16 nField;         /* Number of entries in apMem[] */
  1591         -  u8 flags;           /* Boolean settings.  UNPACKED_... below */
         1604  +  i8 default_rc;      /* Comparison result if keys are equal */
  1592   1605     Mem *aMem;          /* Values */
         1606  +  int r1;             /* Value to return if (lhs > rhs) */
         1607  +  int r2;             /* Value to return if (rhs < lhs) */
  1593   1608   };
  1594   1609   
  1595         -/*
  1596         -** Allowed values of UnpackedRecord.flags
  1597         -*/
  1598         -#define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
  1599         -#define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
  1600   1610   
  1601   1611   /*
  1602   1612   ** Each SQL index is represented in memory by an
  1603   1613   ** instance of the following structure.
  1604   1614   **
  1605   1615   ** The columns of the table that are to be indexed are described
  1606   1616   ** by the aiColumn[] field of this structure.  For example, suppose
................................................................................
  2352   2362     char *zErrMsg;       /* An error message */
  2353   2363     Vdbe *pVdbe;         /* An engine for executing database bytecode */
  2354   2364     int rc;              /* Return code from execution */
  2355   2365     u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
  2356   2366     u8 checkSchema;      /* Causes schema cookie check after an error */
  2357   2367     u8 nested;           /* Number of nested calls to the parser/code generator */
  2358   2368     u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
  2359         -  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
  2360   2369     u8 nColCache;        /* Number of entries in aColCache[] */
  2361   2370     u8 iColCache;        /* Next entry in aColCache[] to replace */
  2362   2371     u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
  2363   2372     u8 mayAbort;         /* True if statement may throw an ABORT exception */
  2364   2373     u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
  2365   2374     u8 okConstFactor;    /* OK to factor out constants */
  2366   2375     int aTempReg[8];     /* Holding area for temporary registers */
................................................................................
  2665   2674     void (*xLog)(void*,int,const char*); /* Function for logging */
  2666   2675     void *pLogArg;                       /* First argument to xLog() */
  2667   2676     int bLocaltimeFault;              /* True to fail localtime() calls */
  2668   2677   #ifdef SQLITE_ENABLE_SQLLOG
  2669   2678     void(*xSqllog)(void*,sqlite3*,const char*, int);
  2670   2679     void *pSqllogArg;
  2671   2680   #endif
         2681  +#ifdef SQLITE_VDBE_COVERAGE
         2682  +  /* The following callback (if not NULL) is invoked on every VDBE branch
         2683  +  ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
         2684  +  */
         2685  +  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
         2686  +  void *pVdbeBranchArg;                                     /* 1st argument */
         2687  +#endif
  2672   2688   };
  2673   2689   
  2674   2690   /*
  2675   2691   ** This macro is used inside of assert() statements to indicate that
  2676   2692   ** the assert is only valid on a well-formed database.  Instead of:
  2677   2693   **
  2678   2694   **     assert( X );
................................................................................
  2998   3014   #ifndef SQLITE_OMIT_AUTOINCREMENT
  2999   3015     void sqlite3AutoincrementBegin(Parse *pParse);
  3000   3016     void sqlite3AutoincrementEnd(Parse *pParse);
  3001   3017   #else
  3002   3018   # define sqlite3AutoincrementBegin(X)
  3003   3019   # define sqlite3AutoincrementEnd(X)
  3004   3020   #endif
  3005         -int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  3006   3021   void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  3007   3022   void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  3008   3023   IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  3009   3024   int sqlite3IdListIndex(IdList*,const char*);
  3010   3025   SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  3011   3026   SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  3012   3027   SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
................................................................................
  3046   3061   void sqlite3ExprCodeMove(Parse*, int, int, int);
  3047   3062   void sqlite3ExprCacheStore(Parse*, int, int, int);
  3048   3063   void sqlite3ExprCachePush(Parse*);
  3049   3064   void sqlite3ExprCachePop(Parse*, int);
  3050   3065   void sqlite3ExprCacheRemove(Parse*, int, int);
  3051   3066   void sqlite3ExprCacheClear(Parse*);
  3052   3067   void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  3053         -int sqlite3ExprCode(Parse*, Expr*, int);
         3068  +void sqlite3ExprCode(Parse*, Expr*, int);
         3069  +void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  3054   3070   void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  3055   3071   int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  3056   3072   int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  3057         -int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
         3073  +void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  3058   3074   int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
  3059   3075   #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
  3060   3076   #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
  3061   3077   void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  3062   3078   void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  3063   3079   Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  3064   3080   Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
................................................................................
  3088   3104   void sqlite3CloseSavepoints(sqlite3 *);
  3089   3105   void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  3090   3106   int sqlite3ExprIsConstant(Expr*);
  3091   3107   int sqlite3ExprIsConstantNotJoin(Expr*);
  3092   3108   int sqlite3ExprIsConstantOrFunction(Expr*);
  3093   3109   int sqlite3ExprIsInteger(Expr*, int*);
  3094   3110   int sqlite3ExprCanBeNull(const Expr*);
  3095         -void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  3096   3111   int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  3097   3112   int sqlite3IsRowid(const char*);
  3098   3113   void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
  3099   3114   void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
  3100   3115   int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  3101   3116   void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  3102   3117                                        u8,u8,int,int*);
................................................................................
  3232   3247     (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  3233   3248     sqlite3PutVarint32((A),(B)))
  3234   3249   #define getVarint    sqlite3GetVarint
  3235   3250   #define putVarint    sqlite3PutVarint
  3236   3251   
  3237   3252   
  3238   3253   const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  3239         -void sqlite3TableAffinityStr(Vdbe *, Table *);
         3254  +void sqlite3TableAffinity(Vdbe*, Table*, int);
  3240   3255   char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  3241   3256   int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  3242   3257   char sqlite3ExprAffinity(Expr *pExpr);
  3243   3258   int sqlite3Atoi64(const char*, i64*, int, u8);
  3244   3259   void sqlite3Error(sqlite3*, int, const char*,...);
  3245   3260   void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  3246   3261   u8 sqlite3HexToInt(int h);

Changes to src/tclsqlite.c.

  3926   3926   
  3927   3927     /* Call sqlite3_shutdown() once before doing anything else. This is to
  3928   3928     ** test that sqlite3_shutdown() can be safely called by a process before
  3929   3929     ** sqlite3_initialize() is. */
  3930   3930     sqlite3_shutdown();
  3931   3931   
  3932   3932     Tcl_FindExecutable(argv[0]);
         3933  +  Tcl_SetSystemEncoding(NULL, "utf-8");
  3933   3934     interp = Tcl_CreateInterp();
  3934   3935   
  3935   3936   #if TCLSH==2
  3936   3937     sqlite3_config(SQLITE_CONFIG_SINGLETHREAD);
  3937   3938   #endif
  3938   3939   
  3939   3940     init_all(interp);

Changes to src/test_loadext.c.

    87     87       sqlite3_result_int(context, cur);
    88     88     }
    89     89   }
    90     90   
    91     91   /*
    92     92   ** Extension load function.
    93     93   */
           94  +#ifdef _WIN32
           95  +__declspec(dllexport)
           96  +#endif
    94     97   int testloadext_init(
    95     98     sqlite3 *db, 
    96     99     char **pzErrMsg, 
    97    100     const sqlite3_api_routines *pApi
    98    101   ){
    99    102     int nErr = 0;
   100    103     SQLITE_EXTENSION_INIT2(pApi);
................................................................................
   105    108                             statusFunc, 0, 0);
   106    109     return nErr ? SQLITE_ERROR : SQLITE_OK;
   107    110   }
   108    111   
   109    112   /*
   110    113   ** Another extension entry point. This one always fails.
   111    114   */
          115  +#ifdef _WIN32
          116  +__declspec(dllexport)
          117  +#endif
   112    118   int testbrokenext_init(
   113    119     sqlite3 *db, 
   114    120     char **pzErrMsg, 
   115    121     const sqlite3_api_routines *pApi
   116    122   ){
   117    123     char *zErr;
   118    124     SQLITE_EXTENSION_INIT2(pApi);
   119    125     zErr = sqlite3_mprintf("broken!");
   120    126     *pzErrMsg = zErr;
   121    127     return 1;
   122    128   }

Changes to src/trigger.c.

   562    562   #endif
   563    563   
   564    564     /* Generate code to destroy the database record of the trigger.
   565    565     */
   566    566     assert( pTable!=0 );
   567    567     if( (v = sqlite3GetVdbe(pParse))!=0 ){
   568    568       int base;
          569  +    static const int iLn = __LINE__+2;
   569    570       static const VdbeOpList dropTrigger[] = {
   570    571         { OP_Rewind,     0, ADDR(9),  0},
   571    572         { OP_String8,    0, 1,        0}, /* 1 */
   572    573         { OP_Column,     0, 1,        2},
   573    574         { OP_Ne,         2, ADDR(8),  1},
   574    575         { OP_String8,    0, 1,        0}, /* 4: "trigger" */
   575    576         { OP_Column,     0, 0,        2},
................................................................................
   576    577         { OP_Ne,         2, ADDR(8),  1},
   577    578         { OP_Delete,     0, 0,        0},
   578    579         { OP_Next,       0, ADDR(1),  0}, /* 8 */
   579    580       };
   580    581   
   581    582       sqlite3BeginWriteOperation(pParse, 0, iDb);
   582    583       sqlite3OpenMasterTable(pParse, iDb);
   583         -    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
          584  +    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
   584    585       sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
   585    586       sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
   586    587       sqlite3ChangeCookie(pParse, iDb);
   587    588       sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
   588    589       sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
   589    590       if( pParse->nMem<3 ){
   590    591         pParse->nMem = 3;

Changes to src/update.c.

   386    386       }
   387    387       if( okOnePass ){
   388    388         sqlite3VdbeChangeToNoop(v, addrOpen);
   389    389         nKey = nPk;
   390    390         regKey = iPk;
   391    391       }else{
   392    392         sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
   393         -                        sqlite3IndexAffinityStr(v, pPk), P4_TRANSIENT);
          393  +                        sqlite3IndexAffinityStr(v, pPk), nPk);
   394    394         sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
   395    395       }
   396    396       sqlite3WhereEnd(pWInfo);
   397    397     }
   398    398   
   399    399     /* Initialize the count of updated rows
   400    400     */
................................................................................
   430    430     }
   431    431   
   432    432     /* Top of the update loop */
   433    433     if( okOnePass ){
   434    434       if( aToOpen[iDataCur-iBaseCur] ){
   435    435         assert( pPk!=0 );
   436    436         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
          437  +      VdbeCoverageNeverTaken(v);
   437    438       }
   438    439       labelContinue = labelBreak;
   439    440       sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
          441  +    VdbeCoverage(v);
   440    442     }else if( pPk ){
   441    443       labelContinue = sqlite3VdbeMakeLabel(v);
   442         -    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak);
          444  +    sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
   443    445       addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
   444    446       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
          447  +    VdbeCoverage(v);
   445    448     }else{
   446    449       labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
   447    450                                regOldRowid);
          451  +    VdbeCoverage(v);
   448    452       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
          453  +    VdbeCoverage(v);
   449    454     }
   450    455   
   451    456     /* If the record number will change, set register regNewRowid to
   452    457     ** contain the new value. If the record number is not being modified,
   453    458     ** then regNewRowid is the same register as regOldRowid, which is
   454    459     ** already populated.  */
   455    460     assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
   456    461     if( chngRowid ){
   457    462       sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
   458         -    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
          463  +    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
   459    464     }
   460    465   
   461    466     /* Compute the old pre-UPDATE content of the row being changed, if that
   462    467     ** information is needed */
   463    468     if( chngPk || hasFK || pTrigger ){
   464    469       u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
   465    470       oldmask |= sqlite3TriggerColmask(pParse, 
................................................................................
   520    525       }
   521    526     }
   522    527   
   523    528     /* Fire any BEFORE UPDATE triggers. This happens before constraints are
   524    529     ** verified. One could argue that this is wrong.
   525    530     */
   526    531     if( tmask&TRIGGER_BEFORE ){
   527         -    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
   528         -    sqlite3TableAffinityStr(v, pTab);
          532  +    sqlite3TableAffinity(v, pTab, regNew);
   529    533       sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
   530    534           TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
   531    535   
   532    536       /* The row-trigger may have deleted the row being updated. In this
   533    537       ** case, jump to the next row. No updates or AFTER triggers are 
   534    538       ** required. This behavior - what happens when the row being updated
   535    539       ** is deleted or renamed by a BEFORE trigger - is left undefined in the
   536    540       ** documentation.
   537    541       */
   538    542       if( pPk ){
   539    543         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
          544  +      VdbeCoverage(v);
   540    545       }else{
   541    546         sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
          547  +      VdbeCoverage(v);
   542    548       }
   543    549   
   544    550       /* If it did not delete it, the row-trigger may still have modified 
   545    551       ** some of the columns of the row being updated. Load the values for 
   546    552       ** all columns not modified by the update statement into their 
   547    553       ** registers in case this has happened.
   548    554       */
................................................................................
   570    576       /* Delete the index entries associated with the current record.  */
   571    577       if( bReplace || chngKey ){
   572    578         if( pPk ){
   573    579           j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
   574    580         }else{
   575    581           j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
   576    582         }
          583  +      VdbeCoverageNeverTaken(v);
   577    584       }
   578    585       sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
   579    586   
   580    587       /* If changing the rowid value, or if there are foreign key constraints
   581    588       ** to process, delete the old record. Otherwise, add a noop OP_Delete
   582    589       ** to invoke the pre-update hook.
   583    590       **
................................................................................
   626    633     /* Repeat the above with the next record to be updated, until
   627    634     ** all record selected by the WHERE clause have been updated.
   628    635     */
   629    636     if( okOnePass ){
   630    637       /* Nothing to do at end-of-loop for a single-pass */
   631    638     }else if( pPk ){
   632    639       sqlite3VdbeResolveLabel(v, labelContinue);
   633         -    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop);
          640  +    sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
   634    641     }else{
   635    642       sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
   636    643     }
   637    644     sqlite3VdbeResolveLabel(v, labelBreak);
   638    645   
   639    646     /* Close all tables */
   640    647     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
................................................................................
   755    762     */
   756    763     sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
   757    764     sqlite3Select(pParse, pSelect, &dest);
   758    765   
   759    766     /* Generate code to scan the ephemeral table and call VUpdate. */
   760    767     iReg = ++pParse->nMem;
   761    768     pParse->nMem += pTab->nCol+1;
   762         -  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
          769  +  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
   763    770     sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
   764    771     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
   765    772     for(i=0; i<pTab->nCol; i++){
   766    773       sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
   767    774     }
   768    775     sqlite3VtabMakeWritable(pParse, pTab);
   769    776     sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
   770    777     sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
   771    778     sqlite3MayAbort(pParse);
   772         -  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
          779  +  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
   773    780     sqlite3VdbeJumpHere(v, addr);
   774    781     sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
   775    782   
   776    783     /* Cleanup */
   777    784     sqlite3SelectDelete(db, pSelect);  
   778    785   }
   779    786   #endif /* SQLITE_OMIT_VIRTUALTABLE */

Changes to src/utf.c.

   313    313     }
   314    314     *z = 0;
   315    315     assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
   316    316   
   317    317     sqlite3VdbeMemRelease(pMem);
   318    318     pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
   319    319     pMem->enc = desiredEnc;
   320         -  pMem->flags |= (MEM_Term|MEM_Dyn);
          320  +  pMem->flags |= (MEM_Term);
   321    321     pMem->z = (char*)zOut;
   322    322     pMem->zMalloc = pMem->z;
   323    323   
   324    324   translate_out:
   325    325   #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
   326    326     {
   327    327       char zBuf[100];
................................................................................
   441    441     sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
   442    442     if( db->mallocFailed ){
   443    443       sqlite3VdbeMemRelease(&m);
   444    444       m.z = 0;
   445    445     }
   446    446     assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
   447    447     assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
   448         -  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
   449    448     assert( m.z || db->mallocFailed );
   450    449     return m.z;
   451    450   }
   452    451   
   453    452   /*
   454    453   ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
   455    454   ** Return the number of bytes in the first nChar unicode characters

Changes to src/vdbe.c.

   113    113   */
   114    114   #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
   115    115   # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
   116    116   #else
   117    117   # define UPDATE_MAX_BLOBSIZE(P)
   118    118   #endif
   119    119   
          120  +/*
          121  +** Invoke the VDBE coverage callback, if that callback is defined.  This
          122  +** feature is used for test suite validation only and does not appear an
          123  +** production builds.
          124  +**
          125  +** M is an integer, 2 or 3, that indices how many different ways the
          126  +** branch can go.  It is usually 2.  "I" is the direction the branch
          127  +** goes.  0 means falls through.  1 means branch is taken.  2 means the
          128  +** second alternative branch is taken.
          129  +*/
          130  +#if !defined(SQLITE_VDBE_COVERAGE)
          131  +# define VdbeBranchTaken(I,M)
          132  +#else
          133  +# define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
          134  +  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
          135  +    if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
          136  +      M = iSrcLine;
          137  +      /* Assert the truth of VdbeCoverageAlwaysTaken() and 
          138  +      ** VdbeCoverageNeverTaken() */
          139  +      assert( (M & I)==I );
          140  +    }else{
          141  +      if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
          142  +      sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
          143  +                                      iSrcLine,I,M);
          144  +    }
          145  +  }
          146  +#endif
          147  +
   120    148   /*
   121    149   ** Convert the given register into a string if it isn't one
   122    150   ** already. Return non-zero if a malloc() fails.
   123    151   */
   124    152   #define Stringify(P, enc) \
   125    153      if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
   126    154        { goto no_mem; }
................................................................................
   130    158   ** a pointer to a dynamically allocated string where some other entity
   131    159   ** is responsible for deallocating that string.  Because the register
   132    160   ** does not control the string, it might be deleted without the register
   133    161   ** knowing it.
   134    162   **
   135    163   ** This routine converts an ephemeral string into a dynamically allocated
   136    164   ** string that the register itself controls.  In other words, it
   137         -** converts an MEM_Ephem string into an MEM_Dyn string.
          165  +** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
   138    166   */
   139    167   #define Deephemeralize(P) \
   140    168      if( ((P)->flags&MEM_Ephem)!=0 \
   141    169          && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
   142    170   
   143    171   /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
   144    172   #define isSorter(x) ((x)->pSorter!=0)
................................................................................
   470    498     Mem *pIn2 = 0;             /* 2nd input operand */
   471    499     Mem *pIn3 = 0;             /* 3rd input operand */
   472    500     Mem *pOut = 0;             /* Output operand */
   473    501     int *aPermute = 0;         /* Permutation of columns for OP_Compare */
   474    502     i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
   475    503   #ifdef VDBE_PROFILE
   476    504     u64 start;                 /* CPU clock count at start of opcode */
   477         -  int origPc;                /* Program counter at start of opcode */
   478    505   #endif
   479    506     /*** INSERT STACK UNION HERE ***/
   480    507   
   481    508     assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
   482    509     sqlite3VdbeEnter(p);
   483    510     if( p->rc==SQLITE_NOMEM ){
   484    511       /* This happens if a malloc() inside a call to sqlite3_column_text() or
................................................................................
   532    559     }
   533    560     sqlite3EndBenignMalloc();
   534    561   #endif
   535    562     for(pc=p->pc; rc==SQLITE_OK; pc++){
   536    563       assert( pc>=0 && pc<p->nOp );
   537    564       if( db->mallocFailed ) goto no_mem;
   538    565   #ifdef VDBE_PROFILE
   539         -    origPc = pc;
   540    566       start = sqlite3Hwtime();
   541    567   #endif
   542    568       nVmStep++;
   543    569       pOp = &aOp[pc];
   544    570   
   545    571       /* Only allow tracing if SQLITE_DEBUG is defined.
   546    572       */
................................................................................
   580    606   
   581    607       /* Sanity checking on other operands */
   582    608   #ifdef SQLITE_DEBUG
   583    609       if( (pOp->opflags & OPFLG_IN1)!=0 ){
   584    610         assert( pOp->p1>0 );
   585    611         assert( pOp->p1<=(p->nMem-p->nCursor) );
   586    612         assert( memIsValid(&aMem[pOp->p1]) );
          613  +      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
   587    614         REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
   588    615       }
   589    616       if( (pOp->opflags & OPFLG_IN2)!=0 ){
   590    617         assert( pOp->p2>0 );
   591    618         assert( pOp->p2<=(p->nMem-p->nCursor) );
   592    619         assert( memIsValid(&aMem[pOp->p2]) );
          620  +      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
   593    621         REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
   594    622       }
   595    623       if( (pOp->opflags & OPFLG_IN3)!=0 ){
   596    624         assert( pOp->p3>0 );
   597    625         assert( pOp->p3<=(p->nMem-p->nCursor) );
   598    626         assert( memIsValid(&aMem[pOp->p3]) );
          627  +      assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
   599    628         REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
   600    629       }
   601    630       if( (pOp->opflags & OPFLG_OUT2)!=0 ){
   602    631         assert( pOp->p2>0 );
   603    632         assert( pOp->p2<=(p->nMem-p->nCursor) );
   604    633         memAboutToChange(p, &aMem[pOp->p2]);
   605    634       }
................................................................................
   693    722   **
   694    723   ** Write the current address onto register P1
   695    724   ** and then jump to address P2.
   696    725   */
   697    726   case OP_Gosub: {            /* jump */
   698    727     assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
   699    728     pIn1 = &aMem[pOp->p1];
   700         -  assert( (pIn1->flags & MEM_Dyn)==0 );
          729  +  assert( VdbeMemDynamic(pIn1)==0 );
   701    730     memAboutToChange(p, pIn1);
   702    731     pIn1->flags = MEM_Int;
   703    732     pIn1->u.i = pc;
   704    733     REGISTER_TRACE(pOp->p1, pIn1);
   705    734     pc = pOp->p2 - 1;
   706    735     break;
   707    736   }
................................................................................
   766    795   ** If the co-routine ends with OP_Yield or OP_Return then continue
   767    796   ** to the next instruction.  But if the co-routine ends with
   768    797   ** OP_EndCoroutine, jump immediately to P2.
   769    798   */
   770    799   case OP_Yield: {            /* in1, jump */
   771    800     int pcDest;
   772    801     pIn1 = &aMem[pOp->p1];
   773         -  assert( (pIn1->flags & MEM_Dyn)==0 );
          802  +  assert( VdbeMemDynamic(pIn1)==0 );
   774    803     pIn1->flags = MEM_Int;
   775    804     pcDest = (int)pIn1->u.i;
   776    805     pIn1->u.i = pc;
   777    806     REGISTER_TRACE(pOp->p1, pIn1);
   778    807     pc = pcDest;
   779    808     break;
   780    809   }
................................................................................
   939    968   
   940    969   #ifndef SQLITE_OMIT_UTF16
   941    970     if( encoding!=SQLITE_UTF8 ){
   942    971       rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
   943    972       if( rc==SQLITE_TOOBIG ) goto too_big;
   944    973       if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
   945    974       assert( pOut->zMalloc==pOut->z );
   946         -    assert( pOut->flags & MEM_Dyn );
          975  +    assert( VdbeMemDynamic(pOut)==0 );
   947    976       pOut->zMalloc = 0;
   948    977       pOut->flags |= MEM_Static;
   949         -    pOut->flags &= ~MEM_Dyn;
   950    978       if( pOp->p4type==P4_DYNAMIC ){
   951    979         sqlite3DbFree(db, pOp->p4.z);
   952    980       }
   953    981       pOp->p4type = P4_DYNAMIC;
   954    982       pOp->p4.z = pOut->z;
   955    983       pOp->p1 = pOut->n;
   956    984     }
................................................................................
  1000   1028       VdbeMemRelease(pOut);
  1001   1029       pOut->flags = nullFlag;
  1002   1030       cnt--;
  1003   1031     }
  1004   1032     break;
  1005   1033   }
  1006   1034   
         1035  +/* Opcode: SoftNull P1 * * * *
         1036  +** Synopsis:  r[P1]=NULL
         1037  +**
         1038  +** Set register P1 to have the value NULL as seen by the OP_MakeRecord
         1039  +** instruction, but do not free any string or blob memory associated with
         1040  +** the register, so that if the value was a string or blob that was
         1041  +** previously copied using OP_SCopy, the copies will continue to be valid.
         1042  +*/
         1043  +case OP_SoftNull: {
         1044  +  assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
         1045  +  pOut = &aMem[pOp->p1];
         1046  +  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
         1047  +  break;
         1048  +}
  1007   1049   
  1008   1050   /* Opcode: Blob P1 P2 * P4 *
  1009   1051   ** Synopsis: r[P2]=P4 (len=P1)
  1010   1052   **
  1011   1053   ** P4 points to a blob of data P1 bytes long.  Store this
  1012   1054   ** blob in register P2.
  1013   1055   */
................................................................................
  1064   1106     pIn1 = &aMem[p1];
  1065   1107     pOut = &aMem[p2];
  1066   1108     do{
  1067   1109       assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  1068   1110       assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  1069   1111       assert( memIsValid(pIn1) );
  1070   1112       memAboutToChange(p, pOut);
         1113  +    VdbeMemRelease(pOut);
  1071   1114       zMalloc = pOut->zMalloc;
  1072         -    pOut->zMalloc = 0;
  1073         -    sqlite3VdbeMemMove(pOut, pIn1);
         1115  +    memcpy(pOut, pIn1, sizeof(Mem));
  1074   1116   #ifdef SQLITE_DEBUG
  1075   1117       if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
  1076   1118         pOut->pScopyFrom += p1 - pOp->p2;
  1077   1119       }
  1078   1120   #endif
         1121  +    pIn1->flags = MEM_Undefined;
         1122  +    pIn1->xDel = 0;
  1079   1123       pIn1->zMalloc = zMalloc;
  1080   1124       REGISTER_TRACE(p2++, pOut);
  1081   1125       pIn1++;
  1082   1126       pOut++;
  1083   1127     }while( n-- );
  1084   1128     break;
  1085   1129   }
................................................................................
  1139   1183   
  1140   1184   /* Opcode: ResultRow P1 P2 * * *
  1141   1185   ** Synopsis:  output=r[P1@P2]
  1142   1186   **
  1143   1187   ** The registers P1 through P1+P2-1 contain a single row of
  1144   1188   ** results. This opcode causes the sqlite3_step() call to terminate
  1145   1189   ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  1146         -** structure to provide access to the r[P1]..r[P1+P2-1] values as
         1190  +** structure to provide access to the r(P1)..r(P1+P2-1) values as
  1147   1191   ** the result row.
  1148   1192   */
  1149   1193   case OP_ResultRow: {
  1150   1194     Mem *pMem;
  1151   1195     int i;
  1152   1196     assert( p->nResColumn==pOp->p2 );
  1153   1197     assert( pOp->p1>0 );
................................................................................
  1248   1292     if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  1249   1293     Stringify(pIn1, encoding);
  1250   1294     Stringify(pIn2, encoding);
  1251   1295     nByte = pIn1->n + pIn2->n;
  1252   1296     if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  1253   1297       goto too_big;
  1254   1298     }
  1255         -  MemSetTypeFlag(pOut, MEM_Str);
  1256   1299     if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  1257   1300       goto no_mem;
  1258   1301     }
         1302  +  MemSetTypeFlag(pOut, MEM_Str);
  1259   1303     if( pOut!=pIn2 ){
  1260   1304       memcpy(pOut->z, pIn2->z, pIn2->n);
  1261   1305     }
  1262   1306     memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  1263   1307     pOut->z[nByte]=0;
  1264   1308     pOut->z[nByte+1] = 0;
  1265   1309     pOut->flags |= MEM_Term;
................................................................................
  1630   1674   ** without data loss, then jump immediately to P2, or if P2==0
  1631   1675   ** raise an SQLITE_MISMATCH exception.
  1632   1676   */
  1633   1677   case OP_MustBeInt: {            /* jump, in1 */
  1634   1678     pIn1 = &aMem[pOp->p1];
  1635   1679     if( (pIn1->flags & MEM_Int)==0 ){
  1636   1680       applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
         1681  +    VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  1637   1682       if( (pIn1->flags & MEM_Int)==0 ){
  1638   1683         if( pOp->p2==0 ){
  1639   1684           rc = SQLITE_MISMATCH;
  1640   1685           goto abort_due_to_error;
  1641   1686         }else{
  1642   1687           pc = pOp->p2 - 1;
  1643   1688           break;
................................................................................
  1870   1915       if( pOp->p5 & SQLITE_NULLEQ ){
  1871   1916         /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  1872   1917         ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  1873   1918         ** or not both operands are null.
  1874   1919         */
  1875   1920         assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  1876   1921         assert( (flags1 & MEM_Cleared)==0 );
         1922  +      assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  1877   1923         if( (flags1&MEM_Null)!=0
  1878   1924          && (flags3&MEM_Null)!=0
  1879   1925          && (flags3&MEM_Cleared)==0
  1880   1926         ){
  1881   1927           res = 0;  /* Results are equal */
  1882   1928         }else{
  1883   1929           res = 1;  /* Results are not equal */
  1884   1930         }
  1885   1931       }else{
  1886   1932         /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  1887   1933         ** then the result is always NULL.
  1888   1934         ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  1889   1935         */
  1890         -      if( pOp->p5 & SQLITE_JUMPIFNULL ){
  1891         -        pc = pOp->p2-1;
  1892         -      }else if( pOp->p5 & SQLITE_STOREP2 ){
         1936  +      if( pOp->p5 & SQLITE_STOREP2 ){
  1893   1937           pOut = &aMem[pOp->p2];
  1894   1938           MemSetTypeFlag(pOut, MEM_Null);
  1895   1939           REGISTER_TRACE(pOp->p2, pOut);
         1940  +      }else{
         1941  +        VdbeBranchTaken(2,3);
         1942  +        if( pOp->p5 & SQLITE_JUMPIFNULL ){
         1943  +          pc = pOp->p2-1;
         1944  +        }
  1896   1945         }
  1897   1946         break;
  1898   1947       }
  1899   1948     }else{
  1900   1949       /* Neither operand is NULL.  Do a comparison. */
  1901   1950       affinity = pOp->p5 & SQLITE_AFF_MASK;
  1902   1951       if( affinity ){
................................................................................
  1921   1970   
  1922   1971     if( pOp->p5 & SQLITE_STOREP2 ){
  1923   1972       pOut = &aMem[pOp->p2];
  1924   1973       memAboutToChange(p, pOut);
  1925   1974       MemSetTypeFlag(pOut, MEM_Int);
  1926   1975       pOut->u.i = res;
  1927   1976       REGISTER_TRACE(pOp->p2, pOut);
  1928         -  }else if( res ){
  1929         -    pc = pOp->p2-1;
         1977  +  }else{
         1978  +    VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
         1979  +    if( res ){
         1980  +      pc = pOp->p2-1;
         1981  +    }
  1930   1982     }
  1931         -
  1932   1983     /* Undo any changes made by applyAffinity() to the input registers. */
  1933   1984     pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (flags1&MEM_TypeMask);
  1934   1985     pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (flags3&MEM_TypeMask);
  1935   1986     break;
  1936   1987   }
  1937   1988   
  1938   1989   /* Opcode: Permutation * * * P4 *
................................................................................
  2021   2072   **
  2022   2073   ** Jump to the instruction at address P1, P2, or P3 depending on whether
  2023   2074   ** in the most recent OP_Compare instruction the P1 vector was less than
  2024   2075   ** equal to, or greater than the P2 vector, respectively.
  2025   2076   */
  2026   2077   case OP_Jump: {             /* jump */
  2027   2078     if( iCompare<0 ){
  2028         -    pc = pOp->p1 - 1;
         2079  +    pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
  2029   2080     }else if( iCompare==0 ){
  2030         -    pc = pOp->p2 - 1;
         2081  +    pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
  2031   2082     }else{
  2032         -    pc = pOp->p3 - 1;
         2083  +    pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
  2033   2084     }
  2034   2085     break;
  2035   2086   }
  2036   2087   
  2037   2088   /* Opcode: And P1 P2 P3 * *
  2038   2089   ** Synopsis: r[P3]=(r[P1] && r[P2])
  2039   2090   **
................................................................................
  2129   2180   ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  2130   2181   ** set the flag and fall through to the next instruction.  In other words,
  2131   2182   ** this opcode causes all following up codes up through P2 (but not including
  2132   2183   ** P2) to run just once and skipped on subsequent times through the loop.
  2133   2184   */
  2134   2185   case OP_Once: {             /* jump */
  2135   2186     assert( pOp->p1<p->nOnceFlag );
         2187  +  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  2136   2188     if( p->aOnceFlag[pOp->p1] ){
  2137   2189       pc = pOp->p2-1;
  2138   2190     }else{
  2139   2191       p->aOnceFlag[pOp->p1] = 1;
  2140   2192     }
  2141   2193     break;
  2142   2194   }
................................................................................
  2163   2215   #ifdef SQLITE_OMIT_FLOATING_POINT
  2164   2216       c = sqlite3VdbeIntValue(pIn1)!=0;
  2165   2217   #else
  2166   2218       c = sqlite3VdbeRealValue(pIn1)!=0.0;
  2167   2219   #endif
  2168   2220       if( pOp->opcode==OP_IfNot ) c = !c;
  2169   2221     }
         2222  +  VdbeBranchTaken(c!=0, 2);
  2170   2223     if( c ){
  2171   2224       pc = pOp->p2-1;
  2172   2225     }
  2173   2226     break;
  2174   2227   }
  2175   2228   
  2176   2229   /* Opcode: IsNull P1 P2 * * *
  2177   2230   ** Synopsis:  if r[P1]==NULL goto P2
  2178   2231   **
  2179   2232   ** Jump to P2 if the value in register P1 is NULL.
  2180   2233   */
  2181   2234   case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
  2182   2235     pIn1 = &aMem[pOp->p1];
         2236  +  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  2183   2237     if( (pIn1->flags & MEM_Null)!=0 ){
  2184   2238       pc = pOp->p2 - 1;
  2185   2239     }
  2186   2240     break;
  2187   2241   }
  2188   2242   
  2189   2243   /* Opcode: NotNull P1 P2 * * *
  2190   2244   ** Synopsis: if r[P1]!=NULL goto P2
  2191   2245   **
  2192   2246   ** Jump to P2 if the value in register P1 is not NULL.  
  2193   2247   */
  2194   2248   case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
  2195   2249     pIn1 = &aMem[pOp->p1];
         2250  +  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  2196   2251     if( (pIn1->flags & MEM_Null)==0 ){
  2197   2252       pc = pOp->p2 - 1;
  2198   2253     }
  2199   2254     break;
  2200   2255   }
  2201   2256   
  2202   2257   /* Opcode: Column P1 P2 P3 P4 P5
................................................................................
  2415   2470   
  2416   2471     /* Extract the content for the p2+1-th column.  Control can only
  2417   2472     ** reach this point if aOffset[p2], aOffset[p2+1], and aType[p2] are
  2418   2473     ** all valid.
  2419   2474     */
  2420   2475     assert( p2<pC->nHdrParsed );
  2421   2476     assert( rc==SQLITE_OK );
         2477  +  assert( sqlite3VdbeCheckMemInvariants(pDest) );
  2422   2478     if( pC->szRow>=aOffset[p2+1] ){
  2423   2479       /* This is the common case where the desired content fits on the original
  2424   2480       ** page - where the content is not on an overflow page */
  2425   2481       VdbeMemRelease(pDest);
  2426   2482       sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], aType[p2], pDest);
  2427   2483     }else{
  2428   2484       /* This branch happens only when content is on overflow pages */
................................................................................
  2452   2508       sqlite3VdbeSerialGet(zData, t, pDest);
  2453   2509       /* If we dynamically allocated space to hold the data (in the
  2454   2510       ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  2455   2511       ** dynamically allocated space over to the pDest structure.
  2456   2512       ** This prevents a memory copy. */
  2457   2513       if( sMem.zMalloc ){
  2458   2514         assert( sMem.z==sMem.zMalloc );
  2459         -      assert( !(pDest->flags & MEM_Dyn) );
  2460         -      assert( !(pDest->flags & (MEM_Blob|MEM_Str)) || pDest->z==sMem.z );
         2515  +      assert( VdbeMemDynamic(pDest)==0 );
         2516  +      assert( (pDest->flags & (MEM_Blob|MEM_Str))==0 || pDest->z==sMem.z );
  2461   2517         pDest->flags &= ~(MEM_Ephem|MEM_Static);
  2462   2518         pDest->flags |= MEM_Term;
  2463   2519         pDest->z = sMem.z;
  2464   2520         pDest->zMalloc = sMem.zMalloc;
  2465   2521       }
  2466   2522     }
  2467   2523     pDest->enc = encoding;
................................................................................
  2490   2546     zAffinity = pOp->p4.z;
  2491   2547     assert( zAffinity!=0 );
  2492   2548     assert( zAffinity[pOp->p2]==0 );
  2493   2549     pIn1 = &aMem[pOp->p1];
  2494   2550     while( (cAff = *(zAffinity++))!=0 ){
  2495   2551       assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  2496   2552       assert( memIsValid(pIn1) );
  2497         -    ExpandBlob(pIn1);
  2498   2553       applyAffinity(pIn1, cAff, encoding);
  2499   2554       pIn1++;
  2500   2555     }
  2501   2556     break;
  2502   2557   }
  2503   2558   
  2504   2559   /* Opcode: MakeRecord P1 P2 P3 P4 *
................................................................................
  2568   2623   
  2569   2624     /* Apply the requested affinity to all inputs
  2570   2625     */
  2571   2626     assert( pData0<=pLast );
  2572   2627     if( zAffinity ){
  2573   2628       pRec = pData0;
  2574   2629       do{
  2575         -      applyAffinity(pRec, *(zAffinity++), encoding);
  2576         -    }while( (++pRec)<=pLast );
         2630  +      applyAffinity(pRec++, *(zAffinity++), encoding);
         2631  +      assert( zAffinity[0]==0 || pRec<=pLast );
         2632  +    }while( zAffinity[0] );
  2577   2633     }
  2578   2634   
  2579   2635     /* Loop through the elements that will make up the record to figure
  2580   2636     ** out how much space is required for the new record.
  2581   2637     */
  2582   2638     pRec = pLast;
  2583   2639     do{
................................................................................
  2636   2692       j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  2637   2693     }while( (++pRec)<=pLast );
  2638   2694     assert( i==nHdr );
  2639   2695     assert( j==nByte );
  2640   2696   
  2641   2697     assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  2642   2698     pOut->n = (int)nByte;
  2643         -  pOut->flags = MEM_Blob | MEM_Dyn;
         2699  +  pOut->flags = MEM_Blob;
  2644   2700     pOut->xDel = 0;
  2645   2701     if( nZero ){
  2646   2702       pOut->u.nZero = nZero;
  2647   2703       pOut->flags |= MEM_Zero;
  2648   2704     }
  2649   2705     pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
  2650   2706     REGISTER_TRACE(pOp->p3, pOut);
................................................................................
  2915   2971       rc = SQLITE_ERROR;
  2916   2972     }
  2917   2973     break;
  2918   2974   }
  2919   2975   
  2920   2976   /* Opcode: Transaction P1 P2 P3 P4 P5
  2921   2977   **
  2922         -** Begin a transaction.  The transaction ends when a Commit or Rollback
  2923         -** opcode is encountered.  Depending on the ON CONFLICT setting, the
  2924         -** transaction might also be rolled back if an error is encountered.
         2978  +** Begin a transaction on database P1 if a transaction is not already
         2979  +** active.
         2980  +** If P2 is non-zero, then a write-transaction is started, or if a 
         2981  +** read-transaction is already active, it is upgraded to a write-transaction.
         2982  +** If P2 is zero, then a read-transaction is started.
  2925   2983   **
  2926   2984   ** P1 is the index of the database file on which the transaction is
  2927   2985   ** started.  Index 0 is the main database file and index 1 is the
  2928   2986   ** file used for temporary tables.  Indices of 2 or more are used for
  2929   2987   ** attached databases.
  2930   2988   **
  2931         -** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
  2932         -** obtained on the database file when a write-transaction is started.  No
  2933         -** other process can start another write transaction while this transaction is
  2934         -** underway.  Starting a write transaction also creates a rollback journal. A
  2935         -** write transaction must be started before any changes can be made to the
  2936         -** database.  If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
  2937         -** also obtained on the file.
  2938         -**
  2939   2989   ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  2940   2990   ** true (this flag is set if the Vdbe may modify more than one row and may
  2941   2991   ** throw an ABORT exception), a statement transaction may also be opened.
  2942   2992   ** More specifically, a statement transaction is opened iff the database
  2943   2993   ** connection is currently not in autocommit mode, or if there are other
  2944   2994   ** active statements. A statement transaction allows the changes made by this
  2945   2995   ** VDBE to be rolled back after an error without having to roll back the
  2946   2996   ** entire transaction. If no error is encountered, the statement transaction
  2947   2997   ** will automatically commit when the VDBE halts.
  2948   2998   **
  2949         -** If P2 is zero, then a read-lock is obtained on the database file.
  2950         -**
  2951   2999   ** If P5!=0 then this opcode also checks the schema cookie against P3
  2952   3000   ** and the schema generation counter against P4.
  2953   3001   ** The cookie changes its value whenever the database schema changes.
  2954   3002   ** This operation is used to detect when that the cookie has changed
  2955         -** and that the current process needs to reread the schema.
         3003  +** and that the current process needs to reread the schema.  If the schema
         3004  +** cookie in P3 differs from the schema cookie in the database header or
         3005  +** if the schema generation counter in P4 differs from the current
         3006  +** generation counter, then an SQLITE_SCHEMA error is raised and execution
         3007  +** halts.  The sqlite3_step() wrapper function might then reprepare the
         3008  +** statement and rerun it from the beginning.
  2956   3009   */
  2957   3010   case OP_Transaction: {
  2958   3011     Btree *pBt;
  2959   3012     int iMeta;
  2960   3013     int iGen;
  2961   3014   
  2962   3015     assert( p->bIsReader );
................................................................................
  3431   3484   **
  3432   3485   ** Reposition cursor P1 so that it points to the largest entry that 
  3433   3486   ** is less than or equal to the key value. If there are no records 
  3434   3487   ** less than or equal to the key and P2 is not zero, then jump to P2.
  3435   3488   **
  3436   3489   ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  3437   3490   */
  3438         -case OP_SeekLt:         /* jump, in3 */
  3439         -case OP_SeekLe:         /* jump, in3 */
  3440         -case OP_SeekGe:         /* jump, in3 */
  3441         -case OP_SeekGt: {       /* jump, in3 */
         3491  +case OP_SeekLT:         /* jump, in3 */
         3492  +case OP_SeekLE:         /* jump, in3 */
         3493  +case OP_SeekGE:         /* jump, in3 */
         3494  +case OP_SeekGT: {       /* jump, in3 */
  3442   3495     int res;
  3443   3496     int oc;
  3444   3497     VdbeCursor *pC;
  3445   3498     UnpackedRecord r;
  3446   3499     int nField;
  3447   3500     i64 iKey;      /* The rowid we are to seek to */
  3448   3501   
  3449   3502     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  3450   3503     assert( pOp->p2!=0 );
  3451   3504     pC = p->apCsr[pOp->p1];
  3452   3505     assert( pC!=0 );
  3453   3506     assert( pC->pseudoTableReg==0 );
  3454         -  assert( OP_SeekLe == OP_SeekLt+1 );
  3455         -  assert( OP_SeekGe == OP_SeekLt+2 );
  3456         -  assert( OP_SeekGt == OP_SeekLt+3 );
         3507  +  assert( OP_SeekLE == OP_SeekLT+1 );
         3508  +  assert( OP_SeekGE == OP_SeekLT+2 );
         3509  +  assert( OP_SeekGT == OP_SeekLT+3 );
  3457   3510     assert( pC->isOrdered );
  3458   3511     assert( pC->pCursor!=0 );
  3459   3512     oc = pOp->opcode;
  3460   3513     pC->nullRow = 0;
  3461   3514     if( pC->isTable ){
  3462   3515       /* The input value in P3 might be of any type: integer, real, string,
  3463   3516       ** blob, or NULL.  But it needs to be an integer before we can do
................................................................................
  3469   3522   
  3470   3523       /* If the P3 value could not be converted into an integer without
  3471   3524       ** loss of information, then special processing is required... */
  3472   3525       if( (pIn3->flags & MEM_Int)==0 ){
  3473   3526         if( (pIn3->flags & MEM_Real)==0 ){
  3474   3527           /* If the P3 value cannot be converted into any kind of a number,
  3475   3528           ** then the seek is not possible, so jump to P2 */
  3476         -        pc = pOp->p2 - 1;
         3529  +        pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
  3477   3530           break;
  3478   3531         }
  3479   3532   
  3480   3533         /* If the approximation iKey is larger than the actual real search
  3481   3534         ** term, substitute >= for > and < for <=. e.g. if the search term
  3482   3535         ** is 4.9 and the integer approximation 5:
  3483   3536         **
  3484   3537         **        (x >  4.9)    ->     (x >= 5)
  3485   3538         **        (x <= 4.9)    ->     (x <  5)
  3486   3539         */
  3487   3540         if( pIn3->r<(double)iKey ){
  3488         -        assert( OP_SeekGe==(OP_SeekGt-1) );
  3489         -        assert( OP_SeekLt==(OP_SeekLe-1) );
  3490         -        assert( (OP_SeekLe & 0x0001)==(OP_SeekGt & 0x0001) );
  3491         -        if( (oc & 0x0001)==(OP_SeekGt & 0x0001) ) oc--;
         3541  +        assert( OP_SeekGE==(OP_SeekGT-1) );
         3542  +        assert( OP_SeekLT==(OP_SeekLE-1) );
         3543  +        assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
         3544  +        if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  3492   3545         }
  3493   3546   
  3494   3547         /* If the approximation iKey is smaller than the actual real search
  3495   3548         ** term, substitute <= for < and > for >=.  */
  3496   3549         else if( pIn3->r>(double)iKey ){
  3497         -        assert( OP_SeekLe==(OP_SeekLt+1) );
  3498         -        assert( OP_SeekGt==(OP_SeekGe+1) );
  3499         -        assert( (OP_SeekLt & 0x0001)==(OP_SeekGe & 0x0001) );
  3500         -        if( (oc & 0x0001)==(OP_SeekLt & 0x0001) ) oc++;
         3550  +        assert( OP_SeekLE==(OP_SeekLT+1) );
         3551  +        assert( OP_SeekGT==(OP_SeekGE+1) );
         3552  +        assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
         3553  +        if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  3501   3554         }
  3502   3555       } 
  3503   3556       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  3504   3557       if( rc!=SQLITE_OK ){
  3505   3558         goto abort_due_to_error;
  3506   3559       }
  3507   3560       if( res==0 ){
................................................................................
  3512   3565       nField = pOp->p4.i;
  3513   3566       assert( pOp->p4type==P4_INT32 );
  3514   3567       assert( nField>0 );
  3515   3568       r.pKeyInfo = pC->pKeyInfo;
  3516   3569       r.nField = (u16)nField;
  3517   3570   
  3518   3571       /* The next line of code computes as follows, only faster:
  3519         -    **   if( oc==OP_SeekGt || oc==OP_SeekLe ){
  3520         -    **     r.flags = UNPACKED_INCRKEY;
         3572  +    **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
         3573  +    **     r.default_rc = -1;
  3521   3574       **   }else{
  3522         -    **     r.flags = 0;
         3575  +    **     r.default_rc = +1;
  3523   3576       **   }
  3524   3577       */
  3525         -    r.flags = (u8)(UNPACKED_INCRKEY * (1 & (oc - OP_SeekLt)));
  3526         -    assert( oc!=OP_SeekGt || r.flags==UNPACKED_INCRKEY );
  3527         -    assert( oc!=OP_SeekLe || r.flags==UNPACKED_INCRKEY );
  3528         -    assert( oc!=OP_SeekGe || r.flags==0 );
  3529         -    assert( oc!=OP_SeekLt || r.flags==0 );
         3578  +    r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
         3579  +    assert( oc!=OP_SeekGT || r.default_rc==-1 );
         3580  +    assert( oc!=OP_SeekLE || r.default_rc==-1 );
         3581  +    assert( oc!=OP_SeekGE || r.default_rc==+1 );
         3582  +    assert( oc!=OP_SeekLT || r.default_rc==+1 );
  3530   3583   
  3531   3584       r.aMem = &aMem[pOp->p3];
  3532   3585   #ifdef SQLITE_DEBUG
  3533   3586       { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  3534   3587   #endif
  3535   3588       ExpandBlob(r.aMem);
  3536   3589       rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
................................................................................
  3540   3593       pC->rowidIsValid = 0;
  3541   3594     }
  3542   3595     pC->deferredMoveto = 0;
  3543   3596     pC->cacheStatus = CACHE_STALE;
  3544   3597   #ifdef SQLITE_TEST
  3545   3598     sqlite3_search_count++;
  3546   3599   #endif
  3547         -  if( oc>=OP_SeekGe ){  assert( oc==OP_SeekGe || oc==OP_SeekGt );
  3548         -    if( res<0 || (res==0 && oc==OP_SeekGt) ){
         3600  +  if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
         3601  +    if( res<0 || (res==0 && oc==OP_SeekGT) ){
  3549   3602         res = 0;
  3550   3603         rc = sqlite3BtreeNext(pC->pCursor, &res);
  3551   3604         if( rc!=SQLITE_OK ) goto abort_due_to_error;
  3552   3605         pC->rowidIsValid = 0;
  3553   3606       }else{
  3554   3607         res = 0;
  3555   3608       }
  3556   3609     }else{
  3557         -    assert( oc==OP_SeekLt || oc==OP_SeekLe );
  3558         -    if( res>0 || (res==0 && oc==OP_SeekLt) ){
         3610  +    assert( oc==OP_SeekLT || oc==OP_SeekLE );
         3611  +    if( res>0 || (res==0 && oc==OP_SeekLT) ){
  3559   3612         res = 0;
  3560   3613         rc = sqlite3BtreePrevious(pC->pCursor, &res);
  3561   3614         if( rc!=SQLITE_OK ) goto abort_due_to_error;
  3562   3615         pC->rowidIsValid = 0;
  3563   3616       }else{
  3564   3617         /* res might be negative because the table is empty.  Check to
  3565   3618         ** see if this is the case.
  3566   3619         */
  3567   3620         res = sqlite3BtreeEof(pC->pCursor);
  3568   3621       }
  3569   3622     }
  3570   3623     assert( pOp->p2>0 );
         3624  +  VdbeBranchTaken(res!=0,2);
  3571   3625     if( res ){
  3572   3626       pc = pOp->p2 - 1;
  3573   3627     }
  3574   3628     break;
  3575   3629   }
  3576   3630   
  3577   3631   /* Opcode: Seek P1 P2 * * *
................................................................................
  3679   3733       for(ii=0; ii<r.nField; ii++){
  3680   3734         assert( memIsValid(&r.aMem[ii]) );
  3681   3735         ExpandBlob(&r.aMem[ii]);
  3682   3736   #ifdef SQLITE_DEBUG
  3683   3737         if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  3684   3738   #endif
  3685   3739       }
  3686         -    r.flags = UNPACKED_PREFIX_MATCH;
  3687   3740       pIdxKey = &r;
  3688   3741     }else{
  3689   3742       pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  3690   3743           pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  3691   3744       ); 
  3692   3745       if( pIdxKey==0 ) goto no_mem;
  3693   3746       assert( pIn3->flags & MEM_Blob );
  3694   3747       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
  3695   3748       sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  3696         -    pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  3697   3749     }
         3750  +  pIdxKey->default_rc = 0;
  3698   3751     if( pOp->opcode==OP_NoConflict ){
  3699   3752       /* For the OP_NoConflict opcode, take the jump if any of the
  3700   3753       ** input fields are NULL, since any key with a NULL will not
  3701   3754       ** conflict */
  3702   3755       for(ii=0; ii<r.nField; ii++){
  3703   3756         if( r.aMem[ii].flags & MEM_Null ){
  3704         -        pc = pOp->p2 - 1;
         3757  +        pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
  3705   3758           break;
  3706   3759         }
  3707   3760       }
  3708   3761     }
  3709   3762     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  3710   3763     if( pOp->p4.i==0 ){
  3711   3764       sqlite3DbFree(db, pFree);
................................................................................
  3715   3768     }
  3716   3769     pC->seekResult = res;
  3717   3770     alreadyExists = (res==0);
  3718   3771     pC->nullRow = 1-alreadyExists;
  3719   3772     pC->deferredMoveto = 0;
  3720   3773     pC->cacheStatus = CACHE_STALE;
  3721   3774     if( pOp->opcode==OP_Found ){
         3775  +    VdbeBranchTaken(alreadyExists!=0,2);
  3722   3776       if( alreadyExists ) pc = pOp->p2 - 1;
  3723   3777     }else{
         3778  +    VdbeBranchTaken(alreadyExists==0,2);
  3724   3779       if( !alreadyExists ) pc = pOp->p2 - 1;
  3725   3780     }
  3726   3781     break;
  3727   3782   }
  3728   3783   
  3729   3784   /* Opcode: NotExists P1 P2 P3 * *
  3730   3785   ** Synopsis: intkey=r[P3]
................................................................................
  3759   3814     iKey = pIn3->u.i;
  3760   3815     rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  3761   3816     pC->lastRowid = pIn3->u.i;
  3762   3817     pC->rowidIsValid = res==0 ?1:0;
  3763   3818     pC->nullRow = 0;
  3764   3819     pC->cacheStatus = CACHE_STALE;
  3765   3820     pC->deferredMoveto = 0;
         3821  +  VdbeBranchTaken(res!=0,2);
  3766   3822     if( res!=0 ){
  3767   3823       pc = pOp->p2 - 1;
  3768   3824       assert( pC->rowidIsValid==0 );
  3769   3825     }
  3770   3826     pC->seekResult = res;
  3771   3827     break;
  3772   3828   }
................................................................................
  3840   3896       ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
  3841   3897       ** to provide the constant while making all compilers happy.
  3842   3898       */
  3843   3899   #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  3844   3900   #endif
  3845   3901   
  3846   3902       if( !pC->useRandomRowid ){
  3847         -      v = sqlite3BtreeGetCachedRowid(pC->pCursor);
  3848         -      if( v==0 ){
  3849         -        rc = sqlite3BtreeLast(pC->pCursor, &res);
  3850         -        if( rc!=SQLITE_OK ){
  3851         -          goto abort_due_to_error;
  3852         -        }
  3853         -        if( res ){
  3854         -          v = 1;   /* IMP: R-61914-48074 */
         3903  +      rc = sqlite3BtreeLast(pC->pCursor, &res);
         3904  +      if( rc!=SQLITE_OK ){
         3905  +        goto abort_due_to_error;
         3906  +      }
         3907  +      if( res ){
         3908  +        v = 1;   /* IMP: R-61914-48074 */
         3909  +      }else{
         3910  +        assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
         3911  +        rc = sqlite3BtreeKeySize(pC->pCursor, &v);
         3912  +        assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
         3913  +        if( v>=MAX_ROWID ){
         3914  +          pC->useRandomRowid = 1;
  3855   3915           }else{
  3856         -          assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
  3857         -          rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  3858         -          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
  3859         -          if( v>=MAX_ROWID ){
  3860         -            pC->useRandomRowid = 1;
  3861         -          }else{
  3862         -            v++;   /* IMP: R-29538-34987 */
  3863         -          }
         3916  +          v++;   /* IMP: R-29538-34987 */
  3864   3917           }
  3865   3918         }
         3919  +    }
  3866   3920   
  3867   3921   #ifndef SQLITE_OMIT_AUTOINCREMENT
  3868         -      if( pOp->p3 ){
         3922  +    if( pOp->p3 ){
         3923  +      /* Assert that P3 is a valid memory cell. */
         3924  +      assert( pOp->p3>0 );
         3925  +      if( p->pFrame ){
         3926  +        for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
         3927  +        /* Assert that P3 is a valid memory cell. */
         3928  +        assert( pOp->p3<=pFrame->nMem );
         3929  +        pMem = &pFrame->aMem[pOp->p3];
         3930  +      }else{
  3869   3931           /* Assert that P3 is a valid memory cell. */
  3870         -        assert( pOp->p3>0 );
  3871         -        if( p->pFrame ){
  3872         -          for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  3873         -          /* Assert that P3 is a valid memory cell. */
  3874         -          assert( pOp->p3<=pFrame->nMem );
  3875         -          pMem = &pFrame->aMem[pOp->p3];
  3876         -        }else{
  3877         -          /* Assert that P3 is a valid memory cell. */
  3878         -          assert( pOp->p3<=(p->nMem-p->nCursor) );
  3879         -          pMem = &aMem[pOp->p3];
  3880         -          memAboutToChange(p, pMem);
  3881         -        }
  3882         -        assert( memIsValid(pMem) );
         3932  +        assert( pOp->p3<=(p->nMem-p->nCursor) );
         3933  +        pMem = &aMem[pOp->p3];
         3934  +        memAboutToChange(p, pMem);
         3935  +      }
         3936  +      assert( memIsValid(pMem) );
  3883   3937   
  3884         -        REGISTER_TRACE(pOp->p3, pMem);
  3885         -        sqlite3VdbeMemIntegerify(pMem);
  3886         -        assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
  3887         -        if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  3888         -          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
  3889         -          goto abort_due_to_error;
  3890         -        }
  3891         -        if( v<pMem->u.i+1 ){
  3892         -          v = pMem->u.i + 1;
  3893         -        }
  3894         -        pMem->u.i = v;
         3938  +      REGISTER_TRACE(pOp->p3, pMem);
         3939  +      sqlite3VdbeMemIntegerify(pMem);
         3940  +      assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
         3941  +      if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
         3942  +        rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
         3943  +        goto abort_due_to_error;
         3944  +      }
         3945  +      if( v<pMem->u.i+1 ){
         3946  +        v = pMem->u.i + 1;
  3895   3947         }
         3948  +      pMem->u.i = v;
         3949  +    }
  3896   3950   #endif
  3897         -
  3898         -      sqlite3BtreeSetCachedRowid(pC->pCursor, v<MAX_ROWID ? v+1 : 0);
  3899         -    }
  3900   3951       if( pC->useRandomRowid ){
  3901   3952         /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  3902   3953         ** largest possible integer (9223372036854775807) then the database
  3903   3954         ** engine starts picking positive candidate ROWIDs at random until
  3904   3955         ** it finds one that is not previously used. */
  3905   3956         assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
  3906   3957                                ** an AUTOINCREMENT table. */
................................................................................
  4046   4097     }
  4047   4098     seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  4048   4099     if( pData->flags & MEM_Zero ){
  4049   4100       nZero = pData->u.nZero;
  4050   4101     }else{
  4051   4102       nZero = 0;
  4052   4103     }
  4053         -  sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
  4054   4104     rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  4055   4105                             pData->z, pData->n, nZero,
  4056   4106                             (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  4057   4107     );
  4058   4108     pC->rowidIsValid = 0;
  4059   4109     pC->deferredMoveto = 0;
  4060   4110     pC->cacheStatus = CACHE_STALE;
................................................................................
  4138   4188           pOp->p3
  4139   4189       );
  4140   4190     }
  4141   4191   #endif
  4142   4192   
  4143   4193     if( opflags & OPFLAG_ISNOOP ) break;
  4144   4194   
  4145         -  sqlite3BtreeSetCachedRowid(pC->pCursor, 0);
  4146   4195     rc = sqlite3BtreeDelete(pC->pCursor);
  4147   4196     pC->cacheStatus = CACHE_STALE;
  4148   4197   
  4149   4198     /* Update the change-counter and invoke the update-hook if required. */
  4150   4199     if( opflags & OPFLAG_NCHANGE ){
  4151   4200       p->nChange++;
  4152   4201       assert( pOp->p4.z );
................................................................................
  4191   4240   
  4192   4241     pC = p->apCsr[pOp->p1];
  4193   4242     assert( isSorter(pC) );
  4194   4243     assert( pOp->p4type==P4_INT32 );
  4195   4244     pIn3 = &aMem[pOp->p3];
  4196   4245     nIgnore = pOp->p4.i;
  4197   4246     rc = sqlite3VdbeSorterCompare(pC, pIn3, nIgnore, &res);
         4247  +  VdbeBranchTaken(res!=0,2);
  4198   4248     if( res ){
  4199   4249       pc = pOp->p2-1;
  4200   4250     }
  4201   4251     break;
  4202   4252   };
  4203   4253   
  4204   4254   /* Opcode: SorterData P1 P2 * * *
................................................................................
  4390   4440     res = 0;
  4391   4441     assert( pCrsr!=0 );
  4392   4442     rc = sqlite3BtreeLast(pCrsr, &res);
  4393   4443     pC->nullRow = (u8)res;
  4394   4444     pC->deferredMoveto = 0;
  4395   4445     pC->rowidIsValid = 0;
  4396   4446     pC->cacheStatus = CACHE_STALE;
  4397         -  if( pOp->p2>0 && res ){
  4398         -    pc = pOp->p2 - 1;
         4447  +  if( pOp->p2>0 ){
         4448  +    VdbeBranchTaken(res!=0,2);
         4449  +    if( res ) pc = pOp->p2 - 1;
  4399   4450     }
  4400   4451     break;
  4401   4452   }
  4402   4453   
  4403   4454   
  4404   4455   /* Opcode: Sort P1 P2 * * *
  4405   4456   **
................................................................................
  4448   4499       rc = sqlite3BtreeFirst(pCrsr, &res);
  4449   4500       pC->deferredMoveto = 0;
  4450   4501       pC->cacheStatus = CACHE_STALE;
  4451   4502       pC->rowidIsValid = 0;
  4452   4503     }
  4453   4504     pC->nullRow = (u8)res;
  4454   4505     assert( pOp->p2>0 && pOp->p2<p->nOp );
         4506  +  VdbeBranchTaken(res!=0,2);
  4455   4507     if( res ){
  4456   4508       pc = pOp->p2 - 1;
  4457   4509     }
  4458   4510     break;
  4459   4511   }
  4460   4512   
  4461   4513   /* Opcode: Next P1 P2 P3 P4 P5
................................................................................
  4538   4590     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  4539   4591     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  4540   4592     assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  4541   4593     assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  4542   4594     rc = pOp->p4.xAdvance(pC->pCursor, &res);
  4543   4595   next_tail:
  4544   4596     pC->cacheStatus = CACHE_STALE;
         4597  +  VdbeBranchTaken(res==0,2);
  4545   4598     if( res==0 ){
  4546   4599       pC->nullRow = 0;
  4547   4600       pc = pOp->p2 - 1;
  4548   4601       p->aCounter[pOp->p5]++;
  4549   4602   #ifdef SQLITE_TEST
  4550   4603       sqlite3_search_count++;
  4551   4604   #endif
................................................................................
  4630   4683     pC = p->apCsr[pOp->p1];
  4631   4684     assert( pC!=0 );
  4632   4685     pCrsr = pC->pCursor;
  4633   4686     assert( pCrsr!=0 );
  4634   4687     assert( pOp->p5==0 );
  4635   4688     r.pKeyInfo = pC->pKeyInfo;
  4636   4689     r.nField = (u16)pOp->p3;
  4637         -  r.flags = UNPACKED_PREFIX_MATCH;
         4690  +  r.default_rc = 0;
  4638   4691     r.aMem = &aMem[pOp->p2];
  4639   4692   #ifdef SQLITE_DEBUG
  4640   4693     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  4641   4694   #endif
  4642   4695     rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  4643   4696     if( rc==SQLITE_OK && res==0 ){
  4644   4697       rc = sqlite3BtreeDelete(pCrsr);
................................................................................
  4684   4737     break;
  4685   4738   }
  4686   4739   
  4687   4740   /* Opcode: IdxGE P1 P2 P3 P4 P5
  4688   4741   ** Synopsis: key=r[P3@P4]
  4689   4742   **
  4690   4743   ** The P4 register values beginning with P3 form an unpacked index 
  4691         -** key that omits the ROWID.  Compare this key value against the index 
  4692         -** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
         4744  +** key that omits the PRIMARY KEY.  Compare this key value against the index 
         4745  +** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
         4746  +** fields at the end.
  4693   4747   **
  4694   4748   ** If the P1 index entry is greater than or equal to the key value
  4695   4749   ** then jump to P2.  Otherwise fall through to the next instruction.
         4750  +*/
         4751  +/* Opcode: IdxGT P1 P2 P3 P4 P5
         4752  +** Synopsis: key=r[P3@P4]
  4696   4753   **
  4697         -** If P5 is non-zero then the key value is increased by an epsilon 
  4698         -** prior to the comparison.  This make the opcode work like IdxGT except
  4699         -** that if the key from register P3 is a prefix of the key in the cursor,
  4700         -** the result is false whereas it would be true with IdxGT.
         4754  +** The P4 register values beginning with P3 form an unpacked index 
         4755  +** key that omits the PRIMARY KEY.  Compare this key value against the index 
         4756  +** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
         4757  +** fields at the end.
         4758  +**
         4759  +** If the P1 index entry is greater than the key value
         4760  +** then jump to P2.  Otherwise fall through to the next instruction.
  4701   4761   */
  4702   4762   /* Opcode: IdxLT P1 P2 P3 P4 P5
  4703   4763   ** Synopsis: key=r[P3@P4]
  4704   4764   **
  4705   4765   ** The P4 register values beginning with P3 form an unpacked index 
  4706         -** key that omits the ROWID.  Compare this key value against the index 
  4707         -** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
         4766  +** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
         4767  +** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
         4768  +** ROWID on the P1 index.
  4708   4769   **
  4709   4770   ** If the P1 index entry is less than the key value then jump to P2.
  4710   4771   ** Otherwise fall through to the next instruction.
         4772  +*/
         4773  +/* Opcode: IdxLE P1 P2 P3 P4 P5
         4774  +** Synopsis: key=r[P3@P4]
  4711   4775   **
  4712         -** If P5 is non-zero then the key value is increased by an epsilon prior 
  4713         -** to the comparison.  This makes the opcode work like IdxLE.
         4776  +** The P4 register values beginning with P3 form an unpacked index 
         4777  +** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
         4778  +** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
         4779  +** ROWID on the P1 index.
         4780  +**
         4781  +** If the P1 index entry is less than or equal to the key value then jump
         4782  +** to P2. Otherwise fall through to the next instruction.
  4714   4783   */
         4784  +case OP_IdxLE:          /* jump */
         4785  +case OP_IdxGT:          /* jump */
  4715   4786   case OP_IdxLT:          /* jump */
  4716         -case OP_IdxGE: {        /* jump */
         4787  +case OP_IdxGE:  {       /* jump */
  4717   4788     VdbeCursor *pC;
  4718   4789     int res;
  4719   4790     UnpackedRecord r;
  4720   4791   
  4721   4792     assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  4722   4793     pC = p->apCsr[pOp->p1];
  4723   4794     assert( pC!=0 );
................................................................................
  4724   4795     assert( pC->isOrdered );
  4725   4796     assert( pC->pCursor!=0);
  4726   4797     assert( pC->deferredMoveto==0 );
  4727   4798     assert( pOp->p5==0 || pOp->p5==1 );
  4728   4799     assert( pOp->p4type==P4_INT32 );
  4729   4800     r.pKeyInfo = pC->pKeyInfo;
  4730   4801     r.nField = (u16)pOp->p4.i;
  4731         -  if( pOp->p5 ){
  4732         -    r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
         4802  +  if( pOp->opcode<OP_IdxLT ){
         4803  +    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
         4804  +    r.default_rc = -1;
  4733   4805     }else{
  4734         -    r.flags = UNPACKED_PREFIX_MATCH;
         4806  +    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
         4807  +    r.default_rc = 0;
  4735   4808     }
  4736   4809     r.aMem = &aMem[pOp->p3];
  4737   4810   #ifdef SQLITE_DEBUG
  4738   4811     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  4739   4812   #endif
  4740   4813     res = 0;  /* Not needed.  Only used to silence a warning. */
  4741   4814     rc = sqlite3VdbeIdxKeyCompare(pC, &r, &res);
  4742         -  if( pOp->opcode==OP_IdxLT ){
         4815  +  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
         4816  +  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
         4817  +    assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  4743   4818       res = -res;
  4744   4819     }else{
  4745         -    assert( pOp->opcode==OP_IdxGE );
         4820  +    assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  4746   4821       res++;
  4747   4822     }
         4823  +  VdbeBranchTaken(res>0,2);
  4748   4824     if( res>0 ){
  4749   4825       pc = pOp->p2 - 1 ;
  4750   4826     }
  4751   4827     break;
  4752   4828   }
  4753   4829   
  4754   4830   /* Opcode: Destroy P1 P2 P3 * *
................................................................................
  4833   4909   ** See also: Destroy
  4834   4910   */
  4835   4911   case OP_Clear: {
  4836   4912     int nChange;
  4837   4913    
  4838   4914     nChange = 0;
  4839   4915     assert( p->readOnly==0 );
  4840         -  assert( pOp->p1!=1 );
  4841   4916     assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  4842   4917     rc = sqlite3BtreeClearTable(
  4843   4918         db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  4844   4919     );
  4845   4920     if( pOp->p3 ){
  4846   4921       p->nChange += nChange;
  4847   4922       if( pOp->p3>0 ){
................................................................................
  5102   5177     pIn1 = &aMem[pOp->p1];
  5103   5178     if( (pIn1->flags & MEM_RowSet)==0 
  5104   5179      || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  5105   5180     ){
  5106   5181       /* The boolean index is empty */
  5107   5182       sqlite3VdbeMemSetNull(pIn1);
  5108   5183       pc = pOp->p2 - 1;
         5184  +    VdbeBranchTaken(1,2);
  5109   5185     }else{
  5110   5186       /* A value was pulled from the index */
  5111   5187       sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
         5188  +    VdbeBranchTaken(0,2);
  5112   5189     }
  5113   5190     goto check_for_interrupt;
  5114   5191   }
  5115   5192   
  5116   5193   /* Opcode: RowSetTest P1 P2 P3 P4
  5117   5194   ** Synopsis: if r[P3] in rowset(P1) goto P2
  5118   5195   **
................................................................................
  5156   5233   
  5157   5234     assert( pOp->p4type==P4_INT32 );
  5158   5235     assert( iSet==-1 || iSet>=0 );
  5159   5236     if( iSet ){
  5160   5237       exists = sqlite3RowSetTest(pIn1->u.pRowSet, 
  5161   5238                                  (u8)(iSet>=0 ? iSet & 0xf : 0xff),
  5162   5239                                  pIn3->u.i);
         5240  +    VdbeBranchTaken(exists!=0,2);
  5163   5241       if( exists ){
  5164   5242         pc = pOp->p2 - 1;
  5165   5243         break;
  5166   5244       }
  5167   5245     }
  5168   5246     if( iSet>=0 ){
  5169   5247       sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
................................................................................
  5348   5426   ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  5349   5427   ** is zero (the one that counts deferred constraint violations). If P1 is
  5350   5428   ** zero, the jump is taken if the statement constraint-counter is zero
  5351   5429   ** (immediate foreign key constraint violations).
  5352   5430   */
  5353   5431   case OP_FkIfZero: {         /* jump */
  5354   5432     if( pOp->p1 ){
         5433  +    VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  5355   5434       if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  5356   5435     }else{
         5436  +    VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  5357   5437       if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  5358   5438     }
  5359   5439     break;
  5360   5440   }
  5361   5441   #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  5362   5442   
  5363   5443   #ifndef SQLITE_OMIT_AUTOINCREMENT
................................................................................
  5398   5478   **
  5399   5479   ** It is illegal to use this instruction on a register that does
  5400   5480   ** not contain an integer.  An assertion fault will result if you try.
  5401   5481   */
  5402   5482   case OP_IfPos: {        /* jump, in1 */
  5403   5483     pIn1 = &aMem[pOp->p1];
  5404   5484     assert( pIn1->flags&MEM_Int );
         5485  +  VdbeBranchTaken( pIn1->u.i>0, 2);
  5405   5486     if( pIn1->u.i>0 ){
  5406   5487        pc = pOp->p2 - 1;
  5407   5488     }
  5408   5489     break;
  5409   5490   }
  5410   5491   
  5411   5492   /* Opcode: IfNeg P1 P2 * * *
................................................................................
  5415   5496   **
  5416   5497   ** It is illegal to use this instruction on a register that does
  5417   5498   ** not contain an integer.  An assertion fault will result if you try.
  5418   5499   */
  5419   5500   case OP_IfNeg: {        /* jump, in1 */
  5420   5501     pIn1 = &aMem[pOp->p1];
  5421   5502     assert( pIn1->flags&MEM_Int );
         5503  +  VdbeBranchTaken(pIn1->u.i<0, 2);
  5422   5504     if( pIn1->u.i<0 ){
  5423   5505        pc = pOp->p2 - 1;
  5424   5506     }
  5425   5507     break;
  5426   5508   }
  5427   5509   
  5428   5510   /* Opcode: IfZero P1 P2 P3 * *
................................................................................
  5434   5516   ** It is illegal to use this instruction on a register that does
  5435   5517   ** not contain an integer.  An assertion fault will result if you try.
  5436   5518   */
  5437   5519   case OP_IfZero: {        /* jump, in1 */
  5438   5520     pIn1 = &aMem[pOp->p1];
  5439   5521     assert( pIn1->flags&MEM_Int );
  5440   5522     pIn1->u.i += pOp->p3;
         5523  +  VdbeBranchTaken(pIn1->u.i==0, 2);
  5441   5524     if( pIn1->u.i==0 ){
  5442   5525        pc = pOp->p2 - 1;
  5443   5526     }
  5444   5527     break;
  5445   5528   }
  5446   5529   
  5447   5530   /* Opcode: AggStep * P2 P3 P4 P5
................................................................................
  5705   5788     Btree *pBt;
  5706   5789   
  5707   5790     assert( pOp->p1>=0 && pOp->p1<db->nDb );
  5708   5791     assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  5709   5792     assert( p->readOnly==0 );
  5710   5793     pBt = db->aDb[pOp->p1].pBt;
  5711   5794     rc = sqlite3BtreeIncrVacuum(pBt);
         5795  +  VdbeBranchTaken(rc==SQLITE_DONE,2);
  5712   5796     if( rc==SQLITE_DONE ){
  5713   5797       pc = pOp->p2 - 1;
  5714   5798       rc = SQLITE_OK;
  5715   5799     }
  5716   5800     break;
  5717   5801   }
  5718   5802   #endif
................................................................................
  5911   5995       p->inVtabMethod = 1;
  5912   5996       rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  5913   5997       p->inVtabMethod = 0;
  5914   5998       sqlite3VtabImportErrmsg(p, pVtab);
  5915   5999       if( rc==SQLITE_OK ){
  5916   6000         res = pModule->xEof(pVtabCursor);
  5917   6001       }
  5918         -
         6002  +    VdbeBranchTaken(res!=0,2);
  5919   6003       if( res ){
  5920   6004         pc = pOp->p2 - 1;
  5921   6005       }
  5922   6006     }
  5923   6007     pCur->nullRow = 0;
  5924   6008   
  5925   6009     break;
................................................................................
  6016   6100     p->inVtabMethod = 1;
  6017   6101     rc = pModule->xNext(pCur->pVtabCursor);
  6018   6102     p->inVtabMethod = 0;
  6019   6103     sqlite3VtabImportErrmsg(p, pVtab);
  6020   6104     if( rc==SQLITE_OK ){
  6021   6105       res = pModule->xEof(pCur->pVtabCursor);
  6022   6106     }
  6023         -
         6107  +  VdbeBranchTaken(!res,2);
  6024   6108     if( !res ){
  6025   6109       /* If there is data, jump to P2 */
  6026   6110       pc = pOp->p2 - 1;
  6027   6111     }
  6028   6112     goto check_for_interrupt;
  6029   6113   }
  6030   6114   #endif /* SQLITE_OMIT_VIRTUALTABLE */
................................................................................
  6250   6334       }
  6251   6335   
  6252   6336   #ifdef VDBE_PROFILE
  6253   6337       {
  6254   6338         u64 elapsed = sqlite3Hwtime() - start;
  6255   6339         pOp->cycles += elapsed;
  6256   6340         pOp->cnt++;
  6257         -#if 0
  6258         -        fprintf(stdout, "%10llu ", elapsed);
  6259         -        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  6260         -#endif
  6261   6341       }
  6262   6342   #endif
  6263   6343   
  6264   6344       /* The following code adds nothing to the actual functionality
  6265   6345       ** of the program.  It is only here for testing and debugging.
  6266   6346       ** On the other hand, it does burn CPU cycles every time through
  6267   6347       ** the evaluator loop.  So we can leave it out when NDEBUG is defined.

Changes to src/vdbe.h.

    62     62       Table *pTab;           /* Used when p4type is P4_TABLE */
    63     63       int (*xAdvance)(BtCursor *, int *);
    64     64     } p4;
    65     65   #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
    66     66     char *zComment;          /* Comment to improve readability */
    67     67   #endif
    68     68   #ifdef VDBE_PROFILE
    69         -  int cnt;                 /* Number of times this instruction was executed */
           69  +  u32 cnt;                 /* Number of times this instruction was executed */
    70     70     u64 cycles;              /* Total time spent executing this instruction */
    71     71   #endif
           72  +#ifdef SQLITE_VDBE_COVERAGE
           73  +  int iSrcLine;            /* Source-code line that generated this opcode */
           74  +#endif
    72     75   };
    73     76   typedef struct VdbeOp VdbeOp;
    74     77   
    75     78   
    76     79   /*
    77     80   ** A sub-routine used to implement a trigger program.
    78     81   */
................................................................................
   165    168   Vdbe *sqlite3VdbeCreate(Parse*);
   166    169   int sqlite3VdbeAddOp0(Vdbe*,int);
   167    170   int sqlite3VdbeAddOp1(Vdbe*,int,int);
   168    171   int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
   169    172   int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
   170    173   int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
   171    174   int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
   172         -int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
          175  +int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
   173    176   void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
   174    177   void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
   175    178   void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
   176    179   void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
   177    180   void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
   178    181   void sqlite3VdbeJumpHere(Vdbe*, int addr);
   179    182   void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
................................................................................
   206    209   sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
   207    210   void sqlite3VdbeSetVarmask(Vdbe*, int);
   208    211   #ifndef SQLITE_OMIT_TRACE
   209    212     char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   210    213   #endif
   211    214   
   212    215   void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
   213         -int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
          216  +int sqlite3VdbeRecordCompare(int,const void*,const UnpackedRecord*,int);
   214    217   UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
          218  +
          219  +typedef int (*RecordCompare)(int,const void*,const UnpackedRecord*,int);
          220  +RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
   215    221   
   216    222   #ifndef SQLITE_OMIT_TRIGGER
   217    223   void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
   218    224   #endif
   219    225   
   220    226   /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
   221    227   ** each VDBE opcode.
................................................................................
   236    242   # endif
   237    243   #else
   238    244   # define VdbeComment(X)
   239    245   # define VdbeNoopComment(X)
   240    246   # define VdbeModuleComment(X)
   241    247   #endif
   242    248   
          249  +/*
          250  +** The VdbeCoverage macros are used to set a coverage testing point
          251  +** for VDBE branch instructions.  The coverage testing points are line
          252  +** numbers in the sqlite3.c source file.  VDBE branch coverage testing
          253  +** only works with an amalagmation build.  That's ok since a VDBE branch
          254  +** coverage build designed for testing the test suite only.  No application
          255  +** should ever ship with VDBE branch coverage measuring turned on.
          256  +**
          257  +**    VdbeCoverage(v)                  // Mark the previously coded instruction
          258  +**                                     // as a branch
          259  +**
          260  +**    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
          261  +**
          262  +**    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
          263  +**
          264  +**    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
          265  +**
          266  +** Every VDBE branch operation must be tagged with one of the macros above.
          267  +** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
          268  +** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
          269  +** routine in vdbe.c, alerting the developer to the missed tag.
          270  +*/
          271  +#ifdef SQLITE_VDBE_COVERAGE
          272  +  void sqlite3VdbeSetLineNumber(Vdbe*,int);
          273  +# define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
          274  +# define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
          275  +# define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
          276  +# define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
          277  +#else
          278  +# define VdbeCoverage(v)
          279  +# define VdbeCoverageIf(v,x)
          280  +# define VdbeCoverageAlwaysTaken(v)
          281  +# define VdbeCoverageNeverTaken(v)
          282  +#endif
          283  +
   243    284   #endif

Changes to src/vdbeInt.h.

   204    204   
   205    205   /* Whenever Mem contains a valid string or blob representation, one of
   206    206   ** the following flags must be set to determine the memory management
   207    207   ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
   208    208   ** string is \000 or \u0000 terminated
   209    209   */
   210    210   #define MEM_Term      0x0200   /* String rep is nul terminated */
   211         -#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
          211  +#define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
   212    212   #define MEM_Static    0x0800   /* Mem.z points to a static string */
   213    213   #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
   214    214   #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
   215    215   #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
   216    216   #ifdef SQLITE_OMIT_INCRBLOB
   217    217     #undef MEM_Zero
   218    218     #define MEM_Zero 0x0000
................................................................................
   406    406   u32 sqlite3VdbeSerialTypeLen(u32);
   407    407   u32 sqlite3VdbeSerialType(Mem*, int);
   408    408   u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
   409    409   u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
   410    410   void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
   411    411   
   412    412   int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
   413         -int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
          413  +int sqlite3VdbeIdxKeyCompare(VdbeCursor*,const UnpackedRecord*,int*);
   414    414   int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
   415    415   int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
   416    416   int sqlite3VdbeExec(Vdbe*);
   417    417   int sqlite3VdbeList(Vdbe*);
   418    418   int sqlite3VdbeHalt(Vdbe*);
   419    419   int sqlite3VdbeChangeEncoding(Mem *, int);
   420    420   int sqlite3VdbeMemTooBig(Mem*);
................................................................................
   473    473   #else
   474    474   # define sqlite3VdbeEnter(X)
   475    475   # define sqlite3VdbeLeave(X)
   476    476   #endif
   477    477   
   478    478   #ifdef SQLITE_DEBUG
   479    479   void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
          480  +int sqlite3VdbeCheckMemInvariants(Mem*);
   480    481   #endif
   481    482   
   482    483   #ifndef SQLITE_OMIT_FOREIGN_KEY
   483    484   int sqlite3VdbeCheckFk(Vdbe *, int);
   484    485   #else
   485    486   # define sqlite3VdbeCheckFk(p,i) 0
   486    487   #endif

Changes to src/vdbeaux.c.

   171    171       test_addop_breakpoint();
   172    172     }
   173    173   #endif
   174    174   #ifdef VDBE_PROFILE
   175    175     pOp->cycles = 0;
   176    176     pOp->cnt = 0;
   177    177   #endif
          178  +#ifdef SQLITE_VDBE_COVERAGE
          179  +  pOp->iSrcLine = 0;
          180  +#endif
   178    181     return i;
   179    182   }
   180    183   int sqlite3VdbeAddOp0(Vdbe *p, int op){
   181    184     return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
   182    185   }
   183    186   int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
   184    187     return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
................................................................................
   532    535     return aOp;
   533    536   }
   534    537   
   535    538   /*
   536    539   ** Add a whole list of operations to the operation stack.  Return the
   537    540   ** address of the first operation added.
   538    541   */
   539         -int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
          542  +int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
   540    543     int addr;
   541    544     assert( p->magic==VDBE_MAGIC_INIT );
   542    545     if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p) ){
   543    546       return 0;
   544    547     }
   545    548     addr = p->nOp;
   546    549     if( ALWAYS(nOp>0) ){
................................................................................
   559    562         }
   560    563         pOut->p3 = pIn->p3;
   561    564         pOut->p4type = P4_NOTUSED;
   562    565         pOut->p4.p = 0;
   563    566         pOut->p5 = 0;
   564    567   #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
   565    568         pOut->zComment = 0;
          569  +#endif
          570  +#ifdef SQLITE_VDBE_COVERAGE
          571  +      pOut->iSrcLine = iLineno+i;
          572  +#else
          573  +      (void)iLineno;
   566    574   #endif
   567    575   #ifdef SQLITE_DEBUG
   568    576         if( p->db->flags & SQLITE_VdbeAddopTrace ){
   569    577           sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
   570    578         }
   571    579   #endif
   572    580       }
................................................................................
   848    856       va_start(ap, zFormat);
   849    857       vdbeVComment(p, zFormat, ap);
   850    858       va_end(ap);
   851    859     }
   852    860   }
   853    861   #endif  /* NDEBUG */
   854    862   
          863  +#ifdef SQLITE_VDBE_COVERAGE
          864  +/*
          865  +** Set the value if the iSrcLine field for the previously coded instruction.
          866  +*/
          867  +void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
          868  +  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
          869  +}
          870  +#endif /* SQLITE_VDBE_COVERAGE */
          871  +
   855    872   /*
   856    873   ** Return the opcode for a given address.  If the address is -1, then
   857    874   ** return the most recently inserted opcode.
   858    875   **
   859    876   ** If a memory allocation error has occurred prior to the calling of this
   860    877   ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
   861    878   ** is readable but not writable, though it is cast to a writable value.
................................................................................
  1171   1188     char zCom[100];
  1172   1189     static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  1173   1190     if( pOut==0 ) pOut = stdout;
  1174   1191     zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  1175   1192   #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  1176   1193     displayComment(pOp, zP4, zCom, sizeof(zCom));
  1177   1194   #else
  1178         -  zCom[0] = 0
         1195  +  zCom[0] = 0;
  1179   1196   #endif
  1180   1197     /* NB:  The sqlite3OpcodeName() function is implemented by code created
  1181   1198     ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  1182   1199     ** information from the vdbe.c source text */
  1183   1200     fprintf(pOut, zFormat1, pc, 
  1184   1201         sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  1185   1202         zCom
................................................................................
  1200   1217         for(pEnd=&p[N]; p<pEnd; p++){
  1201   1218           sqlite3DbFree(db, p->zMalloc);
  1202   1219         }
  1203   1220         return;
  1204   1221       }
  1205   1222       for(pEnd=&p[N]; p<pEnd; p++){
  1206   1223         assert( (&p[1])==pEnd || p[0].db==p[1].db );
         1224  +      assert( sqlite3VdbeCheckMemInvariants(p) );
  1207   1225   
  1208   1226         /* This block is really an inlined version of sqlite3VdbeMemRelease()
  1209   1227         ** that takes advantage of the fact that the memory cell value is 
  1210   1228         ** being set to NULL after releasing any dynamic resources.
  1211   1229         **
  1212   1230         ** The justification for duplicating code is that according to 
  1213   1231         ** callgrind, this causes a certain test case to hit the CPU 4.7 
................................................................................
  1393   1411       pMem->memType = MEM_Int;
  1394   1412       pMem++;
  1395   1413   
  1396   1414       if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
  1397   1415         assert( p->db->mallocFailed );
  1398   1416         return SQLITE_ERROR;
  1399   1417       }
  1400         -    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
         1418  +    pMem->flags = MEM_Str|MEM_Term;
  1401   1419       zP4 = displayP4(pOp, pMem->z, 32);
  1402   1420       if( zP4!=pMem->z ){
  1403   1421         sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  1404   1422       }else{
  1405   1423         assert( pMem->z!=0 );
  1406   1424         pMem->n = sqlite3Strlen30(pMem->z);
  1407   1425         pMem->enc = SQLITE_UTF8;
................................................................................
  1410   1428       pMem++;
  1411   1429   
  1412   1430       if( p->explain==1 ){
  1413   1431         if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  1414   1432           assert( p->db->mallocFailed );
  1415   1433           return SQLITE_ERROR;
  1416   1434         }
  1417         -      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
         1435  +      pMem->flags = MEM_Str|MEM_Term;
  1418   1436         pMem->n = 2;
  1419   1437         sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
  1420   1438         pMem->memType = MEM_Str;
  1421   1439         pMem->enc = SQLITE_UTF8;
  1422   1440         pMem++;
  1423   1441     
  1424   1442   #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  1425   1443         if( sqlite3VdbeMemGrow(pMem, 500, 0) ){
  1426   1444           assert( p->db->mallocFailed );
  1427   1445           return SQLITE_ERROR;
  1428   1446         }
  1429         -      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
         1447  +      pMem->flags = MEM_Str|MEM_Term;
  1430   1448         pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  1431   1449         pMem->memType = MEM_Str;
  1432   1450         pMem->enc = SQLITE_UTF8;
  1433   1451   #else
  1434   1452         pMem->flags = MEM_Null;                       /* Comment */
  1435   1453         pMem->memType = MEM_Null;
  1436   1454   #endif
................................................................................
  2549   2567       if( out ){
  2550   2568         int i;
  2551   2569         fprintf(out, "---- ");
  2552   2570         for(i=0; i<p->nOp; i++){
  2553   2571           fprintf(out, "%02x", p->aOp[i].opcode);
  2554   2572         }
  2555   2573         fprintf(out, "\n");
         2574  +      if( p->zSql ){
         2575  +        char c, pc = 0;
         2576  +        fprintf(out, "-- ");
         2577  +        for(i=0; (c = p->zSql[i])!=0; i++){
         2578  +          if( pc=='\n' ) fprintf(out, "-- ");
         2579  +          putc(c, out);
         2580  +          pc = c;
         2581  +        }
         2582  +        if( pc!='\n' ) fprintf(out, "\n");
         2583  +      }
  2556   2584         for(i=0; i<p->nOp; i++){
  2557         -        fprintf(out, "%6d %10lld %8lld ",
         2585  +        char zHdr[100];
         2586  +        sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  2558   2587              p->aOp[i].cnt,
  2559   2588              p->aOp[i].cycles,
  2560   2589              p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  2561   2590           );
         2591  +        fprintf(out, "%s", zHdr);
  2562   2592           sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  2563   2593         }
  2564   2594         fclose(out);
  2565   2595       }
  2566   2596     }
  2567   2597   #endif
  2568   2598     p->iCurrentTime = 0;
................................................................................
  2909   2939       return len;
  2910   2940     }
  2911   2941   
  2912   2942     /* NULL or constants 0 or 1 */
  2913   2943     return 0;
  2914   2944   }
  2915   2945   
         2946  +/* Input "x" is a sequence of unsigned characters that represent a
         2947  +** big-endian integer.  Return the equivalent native integer
         2948  +*/
         2949  +#define ONE_BYTE_INT(x)    ((i8)(x)[0])
         2950  +#define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
         2951  +#define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
         2952  +#define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
         2953  +
  2916   2954   /*
  2917   2955   ** Deserialize the data blob pointed to by buf as serial type serial_type
  2918   2956   ** and store the result in pMem.  Return the number of bytes read.
  2919   2957   */ 
  2920   2958   u32 sqlite3VdbeSerialGet(
  2921   2959     const unsigned char *buf,     /* Buffer to deserialize from */
  2922   2960     u32 serial_type,              /* Serial type to deserialize */
  2923   2961     Mem *pMem                     /* Memory cell to write value into */
  2924   2962   ){
  2925   2963     u64 x;
  2926   2964     u32 y;
  2927         -  int i;
  2928   2965     switch( serial_type ){
  2929   2966       case 10:   /* Reserved for future use */
  2930   2967       case 11:   /* Reserved for future use */
  2931   2968       case 0: {  /* NULL */
  2932   2969         pMem->flags = MEM_Null;
  2933   2970         break;
  2934   2971       }
  2935   2972       case 1: { /* 1-byte signed integer */
  2936         -      pMem->u.i = (signed char)buf[0];
         2973  +      pMem->u.i = ONE_BYTE_INT(buf);
  2937   2974         pMem->flags = MEM_Int;
  2938   2975         return 1;
  2939   2976       }
  2940   2977       case 2: { /* 2-byte signed integer */
  2941         -      i = 256*(signed char)buf[0] | buf[1];
  2942         -      pMem->u.i = (i64)i;
         2978  +      pMem->u.i = TWO_BYTE_INT(buf);
  2943   2979         pMem->flags = MEM_Int;
  2944   2980         return 2;
  2945   2981       }
  2946   2982       case 3: { /* 3-byte signed integer */
  2947         -      i = 65536*(signed char)buf[0] | (buf[1]<<8) | buf[2];
  2948         -      pMem->u.i = (i64)i;
         2983  +      pMem->u.i = THREE_BYTE_INT(buf);
  2949   2984         pMem->flags = MEM_Int;
  2950   2985         return 3;
  2951   2986       }
  2952   2987       case 4: { /* 4-byte signed integer */
  2953         -      y = ((unsigned)buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
         2988  +      y = FOUR_BYTE_UINT(buf);
  2954   2989         pMem->u.i = (i64)*(int*)&y;
  2955   2990         pMem->flags = MEM_Int;
  2956   2991         return 4;
  2957   2992       }
  2958   2993       case 5: { /* 6-byte signed integer */
  2959         -      x = 256*(signed char)buf[0] + buf[1];
  2960         -      y = ((unsigned)buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  2961         -      x = (x<<32) | y;
  2962         -      pMem->u.i = *(i64*)&x;
         2994  +      pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  2963   2995         pMem->flags = MEM_Int;
  2964   2996         return 6;
  2965   2997       }
  2966   2998       case 6:   /* 8-byte signed integer */
  2967   2999       case 7: { /* IEEE floating point */
  2968   3000   #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  2969   3001         /* Verify that integers and floating point values use the same
................................................................................
  2973   3005         */
  2974   3006         static const u64 t1 = ((u64)0x3ff00000)<<32;
  2975   3007         static const double r1 = 1.0;
  2976   3008         u64 t2 = t1;
  2977   3009         swapMixedEndianFloat(t2);
  2978   3010         assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  2979   3011   #endif
  2980         -      x = ((unsigned)buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  2981         -      y = ((unsigned)buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
         3012  +      x = FOUR_BYTE_UINT(buf);
         3013  +      y = FOUR_BYTE_UINT(buf+4);
  2982   3014         x = (x<<32) | y;
  2983   3015         if( serial_type==6 ){
  2984   3016           pMem->u.i = *(i64*)&x;
  2985   3017           pMem->flags = MEM_Int;
  2986   3018         }else{
  2987   3019           assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  2988   3020           swapMixedEndianFloat(x);
................................................................................
  3070   3102     const unsigned char *aKey = (const unsigned char *)pKey;
  3071   3103     int d; 
  3072   3104     u32 idx;                        /* Offset in aKey[] to read from */
  3073   3105     u16 u;                          /* Unsigned loop counter */
  3074   3106     u32 szHdr;
  3075   3107     Mem *pMem = p->aMem;
  3076   3108   
  3077         -  p->flags = 0;
         3109  +  p->default_rc = 0;
  3078   3110     assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  3079   3111     idx = getVarint32(aKey, szHdr);
  3080   3112     d = szHdr;
  3081   3113     u = 0;
  3082   3114     while( idx<szHdr && u<p->nField && d<=nKey ){
  3083   3115       u32 serial_type;
  3084   3116   
................................................................................
  3092   3124       pMem++;
  3093   3125       u++;
  3094   3126     }
  3095   3127     assert( u<=pKeyInfo->nField + 1 );
  3096   3128     p->nField = u;
  3097   3129   }
  3098   3130   
         3131  +#if SQLITE_DEBUG
  3099   3132   /*
  3100         -** This function compares the two table rows or index records
  3101         -** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
  3102         -** or positive integer if key1 is less than, equal to or 
  3103         -** greater than key2.  The {nKey1, pKey1} key must be a blob
  3104         -** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
  3105         -** key must be a parsed key such as obtained from
  3106         -** sqlite3VdbeParseRecord.
  3107         -**
  3108         -** Key1 and Key2 do not have to contain the same number of fields.
  3109         -** The key with fewer fields is usually compares less than the 
  3110         -** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
  3111         -** and the common prefixes are equal, then key1 is less than key2.
  3112         -** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  3113         -** equal, then the keys are considered to be equal and
  3114         -** the parts beyond the common prefix are ignored.
         3133  +** This function compares two index or table record keys in the same way
         3134  +** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
         3135  +** this function deserializes and compares values using the
         3136  +** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
         3137  +** in assert() statements to ensure that the optimized code in
         3138  +** sqlite3VdbeRecordCompare() returns results with these two primitives.
  3115   3139   */
  3116         -int sqlite3VdbeRecordCompare(
         3140  +static int vdbeRecordCompareDebug(
  3117   3141     int nKey1, const void *pKey1, /* Left key */
  3118         -  UnpackedRecord *pPKey2        /* Right key */
         3142  +  const UnpackedRecord *pPKey2  /* Right key */
  3119   3143   ){
  3120   3144     u32 d1;            /* Offset into aKey[] of next data element */
  3121   3145     u32 idx1;          /* Offset into aKey[] of next header element */
  3122   3146     u32 szHdr1;        /* Number of bytes in header */
  3123   3147     int i = 0;
  3124   3148     int rc = 0;
  3125   3149     const unsigned char *aKey1 = (const unsigned char *)pKey1;
................................................................................
  3185   3209     /* No memory allocation is ever used on mem1.  Prove this using
  3186   3210     ** the following assert().  If the assert() fails, it indicates a
  3187   3211     ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  3188   3212     */
  3189   3213     assert( mem1.zMalloc==0 );
  3190   3214   
  3191   3215     /* rc==0 here means that one of the keys ran out of fields and
  3192         -  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  3193         -  ** flag is set, then break the tie by treating key2 as larger.
  3194         -  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  3195         -  ** are considered to be equal.  Otherwise, the longer key is the 
  3196         -  ** larger.  As it happens, the pPKey2 will always be the longer
  3197         -  ** if there is a difference.
         3216  +  ** all the fields up to that point were equal. Return the the default_rc
         3217  +  ** value.  */
         3218  +  return pPKey2->default_rc;
         3219  +}
         3220  +#endif
         3221  +
         3222  +/*
         3223  +** Both *pMem1 and *pMem2 contain string values. Compare the two values
         3224  +** using the collation sequence pColl. As usual, return a negative , zero
         3225  +** or positive value if *pMem1 is less than, equal to or greater than 
         3226  +** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
         3227  +*/
         3228  +static int vdbeCompareMemString(
         3229  +  const Mem *pMem1,
         3230  +  const Mem *pMem2,
         3231  +  const CollSeq *pColl
         3232  +){
         3233  +  if( pMem1->enc==pColl->enc ){
         3234  +    /* The strings are already in the correct encoding.  Call the
         3235  +     ** comparison function directly */
         3236  +    return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
         3237  +  }else{
         3238  +    int rc;
         3239  +    const void *v1, *v2;
         3240  +    int n1, n2;
         3241  +    Mem c1;
         3242  +    Mem c2;
         3243  +    memset(&c1, 0, sizeof(c1));
         3244  +    memset(&c2, 0, sizeof(c2));
         3245  +    sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
         3246  +    sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
         3247  +    v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
         3248  +    n1 = v1==0 ? 0 : c1.n;
         3249  +    v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
         3250  +    n2 = v2==0 ? 0 : c2.n;
         3251  +    rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
         3252  +    sqlite3VdbeMemRelease(&c1);
         3253  +    sqlite3VdbeMemRelease(&c2);
         3254  +    return rc;
         3255  +  }
         3256  +}
         3257  +
         3258  +/*
         3259  +** Compare the values contained by the two memory cells, returning
         3260  +** negative, zero or positive if pMem1 is less than, equal to, or greater
         3261  +** than pMem2. Sorting order is NULL's first, followed by numbers (integers
         3262  +** and reals) sorted numerically, followed by text ordered by the collating
         3263  +** sequence pColl and finally blob's ordered by memcmp().
         3264  +**
         3265  +** Two NULL values are considered equal by this function.
         3266  +*/
         3267  +int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
         3268  +  int rc;
         3269  +  int f1, f2;
         3270  +  int combined_flags;
         3271  +
         3272  +  f1 = pMem1->flags;
         3273  +  f2 = pMem2->flags;
         3274  +  combined_flags = f1|f2;
         3275  +  assert( (combined_flags & MEM_RowSet)==0 );
         3276  + 
         3277  +  /* If one value is NULL, it is less than the other. If both values
         3278  +  ** are NULL, return 0.
         3279  +  */
         3280  +  if( combined_flags&MEM_Null ){
         3281  +    return (f2&MEM_Null) - (f1&MEM_Null);
         3282  +  }
         3283  +
         3284  +  /* If one value is a number and the other is not, the number is less.
         3285  +  ** If both are numbers, compare as reals if one is a real, or as integers
         3286  +  ** if both values are integers.
         3287  +  */
         3288  +  if( combined_flags&(MEM_Int|MEM_Real) ){
         3289  +    double r1, r2;
         3290  +    if( (f1 & f2 & MEM_Int)!=0 ){
         3291  +      if( pMem1->u.i < pMem2->u.i ) return -1;
         3292  +      if( pMem1->u.i > pMem2->u.i ) return 1;
         3293  +      return 0;
         3294  +    }
         3295  +    if( (f1&MEM_Real)!=0 ){
         3296  +      r1 = pMem1->r;
         3297  +    }else if( (f1&MEM_Int)!=0 ){
         3298  +      r1 = (double)pMem1->u.i;
         3299  +    }else{
         3300  +      return 1;
         3301  +    }
         3302  +    if( (f2&MEM_Real)!=0 ){
         3303  +      r2 = pMem2->r;
         3304  +    }else if( (f2&MEM_Int)!=0 ){
         3305  +      r2 = (double)pMem2->u.i;
         3306  +    }else{
         3307  +      return -1;
         3308  +    }
         3309  +    if( r1<r2 ) return -1;
         3310  +    if( r1>r2 ) return 1;
         3311  +    return 0;
         3312  +  }
         3313  +
         3314  +  /* If one value is a string and the other is a blob, the string is less.
         3315  +  ** If both are strings, compare using the collating functions.
  3198   3316     */
  3199         -  assert( rc==0 );
  3200         -  if( pPKey2->flags & UNPACKED_INCRKEY ){
  3201         -    rc = -1;
  3202         -  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  3203         -    /* Leave rc==0 */
  3204         -  }else if( idx1<szHdr1 ){
  3205         -    rc = 1;
         3317  +  if( combined_flags&MEM_Str ){
         3318  +    if( (f1 & MEM_Str)==0 ){
         3319  +      return 1;
         3320  +    }
         3321  +    if( (f2 & MEM_Str)==0 ){
         3322  +      return -1;
         3323  +    }
         3324  +
         3325  +    assert( pMem1->enc==pMem2->enc );
         3326  +    assert( pMem1->enc==SQLITE_UTF8 || 
         3327  +            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
         3328  +
         3329  +    /* The collation sequence must be defined at this point, even if
         3330  +    ** the user deletes the collation sequence after the vdbe program is
         3331  +    ** compiled (this was not always the case).
         3332  +    */
         3333  +    assert( !pColl || pColl->xCmp );
         3334  +
         3335  +    if( pColl ){
         3336  +      return vdbeCompareMemString(pMem1, pMem2, pColl);
         3337  +    }
         3338  +    /* If a NULL pointer was passed as the collate function, fall through
         3339  +    ** to the blob case and use memcmp().  */
         3340  +  }
         3341  + 
         3342  +  /* Both values must be blobs.  Compare using memcmp().  */
         3343  +  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
         3344  +  if( rc==0 ){
         3345  +    rc = pMem1->n - pMem2->n;
  3206   3346     }
  3207   3347     return rc;
  3208   3348   }
  3209         - 
         3349  +
         3350  +
         3351  +/*
         3352  +** The first argument passed to this function is a serial-type that
         3353  +** corresponds to an integer - all values between 1 and 9 inclusive 
         3354  +** except 7. The second points to a buffer containing an integer value
         3355  +** serialized according to serial_type. This function deserializes
         3356  +** and returns the value.
         3357  +*/
         3358  +static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
         3359  +  u32 y;
         3360  +  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
         3361  +  switch( serial_type ){
         3362  +    case 0:
         3363  +    case 1:
         3364  +      return ONE_BYTE_INT(aKey);
         3365  +    case 2:
         3366  +      return TWO_BYTE_INT(aKey);
         3367  +    case 3:
         3368  +      return THREE_BYTE_INT(aKey);
         3369  +    case 4: {
         3370  +      y = FOUR_BYTE_UINT(aKey);
         3371  +      return (i64)*(int*)&y;
         3372  +    }
         3373  +    case 5: {
         3374  +      return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
         3375  +    }
         3376  +    case 6: {
         3377  +      u64 x = FOUR_BYTE_UINT(aKey);
         3378  +      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
         3379  +      return (i64)*(i64*)&x;
         3380  +    }
         3381  +  }
         3382  +
         3383  +  return (serial_type - 8);
         3384  +}
         3385  +
         3386  +/*
         3387  +** This function compares the two table rows or index records
         3388  +** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
         3389  +** or positive integer if key1 is less than, equal to or 
         3390  +** greater than key2.  The {nKey1, pKey1} key must be a blob
         3391  +** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
         3392  +** key must be a parsed key such as obtained from
         3393  +** sqlite3VdbeParseRecord.
         3394  +**
         3395  +** If argument bSkip is non-zero, it is assumed that the caller has already
         3396  +** determined that the first fields of the keys are equal.
         3397  +**
         3398  +** Key1 and Key2 do not have to contain the same number of fields. If all 
         3399  +** fields that appear in both keys are equal, then pPKey2->default_rc is 
         3400  +** returned.
         3401  +*/
         3402  +int sqlite3VdbeRecordCompare(
         3403  +  int nKey1, const void *pKey1,   /* Left key */
         3404  +  const UnpackedRecord *pPKey2,   /* Right key */
         3405  +  int bSkip                       /* If true, skip the first field */
         3406  +){
         3407  +  u32 d1;                         /* Offset into aKey[] of next data element */
         3408  +  int i;                          /* Index of next field to compare */
         3409  +  u32 szHdr1;                     /* Size of record header in bytes */
         3410  +  u32 idx1;                       /* Offset of first type in header */
         3411  +  int rc = 0;                     /* Return value */
         3412  +  Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
         3413  +  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
         3414  +  const unsigned char *aKey1 = (const unsigned char *)pKey1;
         3415  +  Mem mem1;
         3416  +
         3417  +  /* If bSkip is true, then the caller has already determined that the first
         3418  +  ** two elements in the keys are equal. Fix the various stack variables so
         3419  +  ** that this routine begins comparing at the second field. */
         3420  +  if( bSkip ){
         3421  +    u32 s1;
         3422  +    idx1 = 1 + getVarint32(&aKey1[1], s1);
         3423  +    szHdr1 = aKey1[0];
         3424  +    d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
         3425  +    i = 1;
         3426  +    pRhs++;
         3427  +  }else{
         3428  +    idx1 = getVarint32(aKey1, szHdr1);
         3429  +    d1 = szHdr1;
         3430  +    i = 0;
         3431  +  }
         3432  +
         3433  +  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
         3434  +  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField 
         3435  +       || CORRUPT_DB );
         3436  +  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
         3437  +  assert( pPKey2->pKeyInfo->nField>0 );
         3438  +  assert( idx1<=szHdr1 || CORRUPT_DB );
         3439  +  do{
         3440  +    u32 serial_type;
         3441  +
         3442  +    /* RHS is an integer */
         3443  +    if( pRhs->flags & MEM_Int ){
         3444  +      serial_type = aKey1[idx1];
         3445  +      if( serial_type>=12 ){
         3446  +        rc = +1;
         3447  +      }else if( serial_type==0 ){
         3448  +        rc = -1;
         3449  +      }else if( serial_type==7 ){
         3450  +        double rhs = (double)pRhs->u.i;
         3451  +        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
         3452  +        if( mem1.r<rhs ){
         3453  +          rc = -1;
         3454  +        }else if( mem1.r>rhs ){
         3455  +          rc = +1;
         3456  +        }
         3457  +      }else{
         3458  +        i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
         3459  +        i64 rhs = pRhs->u.i;
         3460  +        if( lhs<rhs ){
         3461  +          rc = -1;
         3462  +        }else if( lhs>rhs ){
         3463  +          rc = +1;
         3464  +        }
         3465  +      }
         3466  +    }
         3467  +
         3468  +    /* RHS is real */
         3469  +    else if( pRhs->flags & MEM_Real ){
         3470  +      serial_type = aKey1[idx1];
         3471  +      if( serial_type>=12 ){
         3472  +        rc = +1;
         3473  +      }else if( serial_type==0 ){
         3474  +        rc = -1;
         3475  +      }else{
         3476  +        double rhs = pRhs->r;
         3477  +        double lhs;
         3478  +        sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
         3479  +        if( serial_type==7 ){
         3480  +          lhs = mem1.r;
         3481  +        }else{
         3482  +          lhs = (double)mem1.u.i;
         3483  +        }
         3484  +        if( lhs<rhs ){
         3485  +          rc = -1;
         3486  +        }else if( lhs>rhs ){
         3487  +          rc = +1;
         3488  +        }
         3489  +      }
         3490  +    }
         3491  +
         3492  +    /* RHS is a string */
         3493  +    else if( pRhs->flags & MEM_Str ){
         3494  +      getVarint32(&aKey1[idx1], serial_type);
         3495  +      if( serial_type<12 ){
         3496  +        rc = -1;
         3497  +      }else if( !(serial_type & 0x01) ){
         3498  +        rc = +1;
         3499  +      }else{
         3500  +        mem1.n = (serial_type - 12) / 2;
         3501  +        if( (d1+mem1.n) > (unsigned)nKey1 ){
         3502  +          rc = 1;                /* Corruption */
         3503  +        }else if( pKeyInfo->aColl[i] ){
         3504  +          mem1.enc = pKeyInfo->enc;
         3505  +          mem1.db = pKeyInfo->db;
         3506  +          mem1.flags = MEM_Str;
         3507  +          mem1.z = (char*)&aKey1[d1];
         3508  +          rc = vdbeCompareMemString(&mem1, pRhs, pKeyInfo->aColl[i]);
         3509  +        }else{
         3510  +          int nCmp = MIN(mem1.n, pRhs->n);
         3511  +          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
         3512  +          if( rc==0 ) rc = mem1.n - pRhs->n; 
         3513  +        }
         3514  +      }
         3515  +    }
         3516  +
         3517  +    /* RHS is a blob */
         3518  +    else if( pRhs->flags & MEM_Blob ){
         3519  +      getVarint32(&aKey1[idx1], serial_type);
         3520  +      if( serial_type<12 || (serial_type & 0x01) ){
         3521  +        rc = -1;
         3522  +      }else{
         3523  +        int nStr = (serial_type - 12) / 2;
         3524  +        if( (d1+nStr) > (unsigned)nKey1 ){
         3525  +          rc = 1;                /* Corruption */
         3526  +        }else{
         3527  +          int nCmp = MIN(nStr, pRhs->n);
         3528  +          rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
         3529  +          if( rc==0 ) rc = nStr - pRhs->n;
         3530  +        }
         3531  +      }
         3532  +    }
         3533  +
         3534  +    /* RHS is null */
         3535  +    else{
         3536  +      serial_type = aKey1[idx1];
         3537  +      rc = (serial_type!=0);
         3538  +    }
         3539  +
         3540  +    if( rc!=0 ){
         3541  +      if( pKeyInfo->aSortOrder[i] ){
         3542  +        rc = -rc;
         3543  +      }
         3544  +      assert( CORRUPT_DB 
         3545  +          || (rc<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
         3546  +          || (rc>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
         3547  +      );
         3548  +      assert( mem1.zMalloc==0 );  /* See comment below */
         3549  +      return rc;
         3550  +    }
         3551  +
         3552  +    i++;
         3553  +    pRhs++;
         3554  +    d1 += sqlite3VdbeSerialTypeLen(serial_type);
         3555  +    idx1 += sqlite3VarintLen(serial_type);
         3556  +  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
         3557  +
         3558  +  /* No memory allocation is ever used on mem1.  Prove this using
         3559  +  ** the following assert().  If the assert() fails, it indicates a
         3560  +  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
         3561  +  assert( mem1.zMalloc==0 );
         3562  +
         3563  +  /* rc==0 here means that one or both of the keys ran out of fields and
         3564  +  ** all the fields up to that point were equal. Return the the default_rc
         3565  +  ** value.  */
         3566  +  assert( CORRUPT_DB 
         3567  +       || pPKey2->default_rc==vdbeRecordCompareDebug(nKey1, pKey1, pPKey2) 
         3568  +  );
         3569  +  return pPKey2->default_rc;
         3570  +}
         3571  +
         3572  +/*
         3573  +** This function is an optimized version of sqlite3VdbeRecordCompare() 
         3574  +** that (a) the first field of pPKey2 is an integer, and (b) the 
         3575  +** size-of-header varint at the start of (pKey1/nKey1) fits in a single
         3576  +** byte (i.e. is less than 128).
         3577  +*/
         3578  +static int vdbeRecordCompareInt(
         3579  +  int nKey1, const void *pKey1, /* Left key */
         3580  +  const UnpackedRecord *pPKey2, /* Right key */
         3581  +  int bSkip                     /* Ignored */
         3582  +){
         3583  +  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
         3584  +  int serial_type = ((const u8*)pKey1)[1];
         3585  +  int res;
         3586  +  u32 y;
         3587  +  u64 x;
         3588  +  i64 v = pPKey2->aMem[0].u.i;
         3589  +  i64 lhs;
         3590  +  UNUSED_PARAMETER(bSkip);
         3591  +
         3592  +  assert( bSkip==0 );
         3593  +  switch( serial_type ){
         3594  +    case 1: { /* 1-byte signed integer */
         3595  +      lhs = ONE_BYTE_INT(aKey);
         3596  +      break;
         3597  +    }
         3598  +    case 2: { /* 2-byte signed integer */
         3599  +      lhs = TWO_BYTE_INT(aKey);
         3600  +      break;
         3601  +    }
         3602  +    case 3: { /* 3-byte signed integer */
         3603  +      lhs = THREE_BYTE_INT(aKey);
         3604  +      break;
         3605  +    }
         3606  +    case 4: { /* 4-byte signed integer */
         3607  +      y = FOUR_BYTE_UINT(aKey);
         3608  +      lhs = (i64)*(int*)&y;
         3609  +      break;
         3610  +    }
         3611  +    case 5: { /* 6-byte signed integer */
         3612  +      lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
         3613  +      break;
         3614  +    }
         3615  +    case 6: { /* 8-byte signed integer */
         3616  +      x = FOUR_BYTE_UINT(aKey);
         3617  +      x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
         3618  +      lhs = *(i64*)&x;
         3619  +      break;
         3620  +    }
         3621  +    case 8: 
         3622  +      lhs = 0;
         3623  +      break;
         3624  +    case 9:
         3625  +      lhs = 1;
         3626  +      break;
         3627  +
         3628  +    /* This case could be removed without changing the results of running
         3629  +    ** this code. Including it causes gcc to generate a faster switch 
         3630  +    ** statement (since the range of switch targets now starts at zero and
         3631  +    ** is contiguous) but does not cause any duplicate code to be generated
         3632  +    ** (as gcc is clever enough to combine the two like cases). Other 
         3633  +    ** compilers might be similar.  */ 
         3634  +    case 0: case 7:
         3635  +      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
         3636  +
         3637  +    default:
         3638  +      return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 0);
         3639  +  }
         3640  +
         3641  +  if( v>lhs ){
         3642  +    res = pPKey2->r1;
         3643  +  }else if( v<lhs ){
         3644  +    res = pPKey2->r2;
         3645  +  }else if( pPKey2->nField>1 ){
         3646  +    /* The first fields of the two keys are equal. Compare the trailing 
         3647  +    ** fields.  */
         3648  +    res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
         3649  +  }else{
         3650  +    /* The first fields of the two keys are equal and there are no trailing
         3651  +    ** fields. Return pPKey2->default_rc in this case. */
         3652  +    res = pPKey2->default_rc;
         3653  +  }
         3654  +
         3655  +  assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
         3656  +       || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
         3657  +       || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
         3658  +       || CORRUPT_DB
         3659  +  );
         3660  +  return res;
         3661  +}
         3662  +
         3663  +/*
         3664  +** This function is an optimized version of sqlite3VdbeRecordCompare() 
         3665  +** that (a) the first field of pPKey2 is a string, that (b) the first field
         3666  +** uses the collation sequence BINARY and (c) that the size-of-header varint 
         3667  +** at the start of (pKey1/nKey1) fits in a single byte.
         3668  +*/
         3669  +static int vdbeRecordCompareString(
         3670  +  int nKey1, const void *pKey1, /* Left key */
         3671  +  const UnpackedRecord *pPKey2, /* Right key */
         3672  +  int bSkip
         3673  +){
         3674  +  const u8 *aKey1 = (const u8*)pKey1;
         3675  +  int serial_type;
         3676  +  int res;
         3677  +  UNUSED_PARAMETER(bSkip);
         3678  +
         3679  +  assert( bSkip==0 );
         3680  +  getVarint32(&aKey1[1], serial_type);
         3681  +
         3682  +  if( serial_type<12 ){
         3683  +    res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
         3684  +  }else if( !(serial_type & 0x01) ){ 
         3685  +    res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
         3686  +  }else{
         3687  +    int nCmp;
         3688  +    int nStr;
         3689  +    int szHdr = aKey1[0];
         3690  +
         3691  +    nStr = (serial_type-12) / 2;
         3692  +    if( (szHdr + nStr) > nKey1 ) return 0;    /* Corruption */
         3693  +    nCmp = MIN( pPKey2->aMem[0].n, nStr );
         3694  +    res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
         3695  +
         3696  +    if( res==0 ){
         3697  +      res = nStr - pPKey2->aMem[0].n;
         3698  +      if( res==0 ){
         3699  +        if( pPKey2->nField>1 ){
         3700  +          res = sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2, 1);
         3701  +        }else{
         3702  +          res = pPKey2->default_rc;
         3703  +        }
         3704  +      }else if( res>0 ){
         3705  +        res = pPKey2->r2;
         3706  +      }else{
         3707  +        res = pPKey2->r1;
         3708  +      }
         3709  +    }else if( res>0 ){
         3710  +      res = pPKey2->r2;
         3711  +    }else{
         3712  +      res = pPKey2->r1;
         3713  +    }
         3714  +  }
         3715  +
         3716  +  assert( (res==0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)==0)
         3717  +       || (res<0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)<0)
         3718  +       || (res>0 && vdbeRecordCompareDebug(nKey1, pKey1, pPKey2)>0)
         3719  +       || CORRUPT_DB
         3720  +  );
         3721  +  return res;
         3722  +}
         3723  +
         3724  +/*
         3725  +** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
         3726  +** suitable for comparing serialized records to the unpacked record passed
         3727  +** as the only argument.
         3728  +*/
         3729  +RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
         3730  +  /* varintRecordCompareInt() and varintRecordCompareString() both assume
         3731  +  ** that the size-of-header varint that occurs at the start of each record
         3732  +  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
         3733  +  ** also assumes that it is safe to overread a buffer by at least the 
         3734  +  ** maximum possible legal header size plus 8 bytes. Because there is
         3735  +  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
         3736  +  ** buffer passed to varintRecordCompareInt() this makes it convenient to
         3737  +  ** limit the size of the header to 64 bytes in cases where the first field
         3738  +  ** is an integer.
         3739  +  **
         3740  +  ** The easiest way to enforce this limit is to consider only records with
         3741  +  ** 13 fields or less. If the first field is an integer, the maximum legal
         3742  +  ** header size is (12*5 + 1 + 1) bytes.  */
         3743  +  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
         3744  +    int flags = p->aMem[0].flags;
         3745  +    if( p->pKeyInfo->aSortOrder[0] ){
         3746  +      p->r1 = 1;
         3747  +      p->r2 = -1;
         3748  +    }else{
         3749  +      p->r1 = -1;
         3750  +      p->r2 = 1;
         3751  +    }
         3752  +    if( (flags & MEM_Int) ){
         3753  +      return vdbeRecordCompareInt;
         3754  +    }
         3755  +    if( (flags & (MEM_Int|MEM_Real|MEM_Null|MEM_Blob))==0 
         3756  +        && p->pKeyInfo->aColl[0]==0 
         3757  +    ){
         3758  +      return vdbeRecordCompareString;
         3759  +    }
         3760  +  }
         3761  +
         3762  +  return sqlite3VdbeRecordCompare;
         3763  +}
  3210   3764   
  3211   3765   /*
  3212   3766   ** pCur points at an index entry created using the OP_MakeRecord opcode.
  3213   3767   ** Read the rowid (the last field in the record) and store it in *rowid.
  3214   3768   ** Return SQLITE_OK if everything works, or an error code otherwise.
  3215   3769   **
  3216   3770   ** pCur might be pointing to text obtained from a corrupt database file.
................................................................................
  3293   3847   **
  3294   3848   ** pUnpacked is either created without a rowid or is truncated so that it
  3295   3849   ** omits the rowid at the end.  The rowid at the end of the index entry
  3296   3850   ** is ignored as well.  Hence, this routine only compares the prefixes 
  3297   3851   ** of the keys prior to the final rowid, not the entire key.
  3298   3852   */
  3299   3853   int sqlite3VdbeIdxKeyCompare(
  3300         -  VdbeCursor *pC,             /* The cursor to compare against */
  3301         -  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
  3302         -  int *res                    /* Write the comparison result here */
         3854  +  VdbeCursor *pC,                  /* The cursor to compare against */
         3855  +  const UnpackedRecord *pUnpacked, /* Unpacked version of key */
         3856  +  int *res                         /* Write the comparison result here */
  3303   3857   ){
  3304   3858     i64 nCellKey = 0;
  3305   3859     int rc;
  3306   3860     BtCursor *pCur = pC->pCursor;
  3307   3861     Mem m;
  3308   3862   
  3309   3863     assert( sqlite3BtreeCursorIsValid(pCur) );
  3310   3864     VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  3311   3865     assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
  3312         -  /* nCellKey will always be between 0 and 0xffffffff because of the say
         3866  +  /* nCellKey will always be between 0 and 0xffffffff because of the way
  3313   3867     ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  3314   3868     if( nCellKey<=0 || nCellKey>0x7fffffff ){
  3315   3869       *res = 0;
  3316   3870       return SQLITE_CORRUPT_BKPT;
  3317   3871     }
  3318   3872     memset(&m, 0, sizeof(m));
  3319   3873     rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
  3320   3874     if( rc ){
  3321   3875       return rc;
  3322   3876     }
  3323         -  assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  3324         -  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
         3877  +  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked, 0);
  3325   3878     sqlite3VdbeMemRelease(&m);
  3326   3879     return SQLITE_OK;
  3327   3880   }
  3328   3881   
  3329   3882   /*
  3330   3883   ** This routine sets the value to be returned by subsequent calls to
  3331   3884   ** sqlite3_changes() on the database handle 'db'. 

Changes to src/vdbeblob.c.

   131    131     ** uses it to implement the blob_read(), blob_write() and 
   132    132     ** blob_bytes() functions.
   133    133     **
   134    134     ** The sqlite3_blob_close() function finalizes the vdbe program,
   135    135     ** which closes the b-tree cursor and (possibly) commits the 
   136    136     ** transaction.
   137    137     */
          138  +  static const int iLn = __LINE__+4;
   138    139     static const VdbeOpList openBlob[] = {
   139    140       /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
   140    141       {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
   141         -
   142    142       /* One of the following two instructions is replaced by an OP_Noop. */
   143    143       {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
   144    144       {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
   145         -
   146    145       {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
   147    146       {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
   148    147       {OP_Column, 0, 0, 1},          /* 6  */
   149    148       {OP_ResultRow, 1, 0, 0},       /* 7  */
   150    149       {OP_Goto, 0, 4, 0},            /* 8  */
   151    150       {OP_Close, 0, 0, 0},           /* 9  */
   152    151       {OP_Halt, 0, 0, 0},            /* 10 */
................................................................................
   265    264         int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
   266    265   
   267    266   
   268    267         sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags, 
   269    268                              pTab->pSchema->schema_cookie,
   270    269                              pTab->pSchema->iGeneration);
   271    270         sqlite3VdbeChangeP5(v, 1);     
   272         -      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
          271  +      sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
   273    272   
   274    273         /* Make sure a mutex is held on the table to be accessed */
   275    274         sqlite3VdbeUsesBtree(v, iDb); 
   276    275   
   277    276         /* Configure the OP_TableLock instruction */
   278    277   #ifdef SQLITE_OMIT_SHARED_CACHE
   279    278         sqlite3VdbeChangeToNoop(v, 1);

Changes to src/vdbemem.c.

    13     13   ** This file contains code use to manipulate "Mem" structure.  A "Mem"
    14     14   ** stores a single value in the VDBE.  Mem is an opaque structure visible
    15     15   ** only within the VDBE.  Interface routines refer to a Mem using the
    16     16   ** name sqlite_value
    17     17   */
    18     18   #include "sqliteInt.h"
    19     19   #include "vdbeInt.h"
           20  +
           21  +#ifdef SQLITE_DEBUG
           22  +/*
           23  +** Check invariants on a Mem object.
           24  +**
           25  +** This routine is intended for use inside of assert() statements, like
           26  +** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
           27  +*/
           28  +int sqlite3VdbeCheckMemInvariants(Mem *p){
           29  +  /* The MEM_Dyn bit is set if and only if Mem.xDel is a non-NULL destructor
           30  +  ** function for Mem.z 
           31  +  */
           32  +  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
           33  +  assert( (p->flags & MEM_Dyn)!=0 || p->xDel==0 );
           34  +
           35  +  /* If p holds a string or blob, the Mem.z must point to exactly
           36  +  ** one of the following:
           37  +  **
           38  +  **   (1) Memory in Mem.zMalloc and managed by the Mem object
           39  +  **   (2) Memory to be freed using Mem.xDel
           40  +  **   (3) An ephermal string or blob
           41  +  **   (4) A static string or blob
           42  +  */
           43  +  if( (p->flags & (MEM_Str|MEM_Blob)) && p->z!=0 ){
           44  +    assert( 
           45  +      ((p->z==p->zMalloc)? 1 : 0) +
           46  +      ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
           47  +      ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
           48  +      ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
           49  +    );
           50  +  }
           51  +
           52  +  return 1;
           53  +}
           54  +#endif
           55  +
    20     56   
    21     57   /*
    22     58   ** If pMem is an object with a valid string representation, this routine
    23     59   ** ensures the internal encoding for the string representation is
    24     60   ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
    25     61   **
    26     62   ** If pMem is not a string object, or the encoding of the string
................................................................................
    63     99   **
    64    100   ** If the bPreserve argument is true, then copy of the content of
    65    101   ** pMem->z into the new allocation.  pMem must be either a string or
    66    102   ** blob if bPreserve is true.  If bPreserve is false, any prior content
    67    103   ** in pMem->z is discarded.
    68    104   */
    69    105   int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
    70         -  assert( 1 >=
    71         -    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
    72         -    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
    73         -    ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
    74         -    ((pMem->flags&MEM_Static) ? 1 : 0)
    75         -  );
          106  +  assert( sqlite3VdbeCheckMemInvariants(pMem) );
    76    107     assert( (pMem->flags&MEM_RowSet)==0 );
    77    108   
    78    109     /* If the bPreserve flag is set to true, then the memory cell must already
    79    110     ** contain a valid string or blob value.  */
    80    111     assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
    81    112     testcase( bPreserve && pMem->z==0 );
    82    113   
................................................................................
    86    117         pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
    87    118         bPreserve = 0;
    88    119       }else{
    89    120         sqlite3DbFree(pMem->db, pMem->zMalloc);
    90    121         pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
    91    122       }
    92    123       if( pMem->zMalloc==0 ){
    93         -      sqlite3VdbeMemRelease(pMem);
          124  +      VdbeMemRelease(pMem);
    94    125         pMem->flags = MEM_Null;  
    95    126         return SQLITE_NOMEM;
    96    127       }
    97    128     }
    98    129   
    99    130     if( pMem->z && bPreserve && pMem->z!=pMem->zMalloc ){
   100    131       memcpy(pMem->zMalloc, pMem->z, pMem->n);
   101    132     }
   102         -  if( (pMem->flags&MEM_Dyn)!=0 && pMem->xDel ){
   103         -    assert( pMem->xDel!=SQLITE_DYNAMIC );
          133  +  if( (pMem->flags&MEM_Dyn)!=0 ){
          134  +    assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
   104    135       pMem->xDel((void *)(pMem->z));
   105    136     }
   106    137   
   107    138     pMem->z = pMem->zMalloc;
   108         -  pMem->flags &= ~(MEM_Ephem|MEM_Static);
          139  +  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
   109    140     pMem->xDel = 0;
   110    141     return SQLITE_OK;
   111    142   }
   112    143   
   113    144   /*
   114    145   ** Make the given Mem object MEM_Dyn.  In other words, make it so
   115    146   ** that any TEXT or BLOB content is stored in memory obtained from
................................................................................
   270    301   */
   271    302   void sqlite3VdbeMemReleaseExternal(Mem *p){
   272    303     assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
   273    304     if( p->flags&MEM_Agg ){
   274    305       sqlite3VdbeMemFinalize(p, p->u.pDef);
   275    306       assert( (p->flags & MEM_Agg)==0 );
   276    307       sqlite3VdbeMemRelease(p);
   277         -  }else if( p->flags&MEM_Dyn && p->xDel ){
          308  +  }else if( p->flags&MEM_Dyn ){
   278    309       assert( (p->flags&MEM_RowSet)==0 );
   279         -    assert( p->xDel!=SQLITE_DYNAMIC );
          310  +    assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
   280    311       p->xDel((void *)p->z);
   281    312       p->xDel = 0;
   282    313     }else if( p->flags&MEM_RowSet ){
   283    314       sqlite3RowSetClear(p->u.pRowSet);
   284    315     }else if( p->flags&MEM_Frame ){
   285    316       sqlite3VdbeMemSetNull(p);
   286    317     }
................................................................................
   288    319   
   289    320   /*
   290    321   ** Release any memory held by the Mem. This may leave the Mem in an
   291    322   ** inconsistent state, for example with (Mem.z==0) and
   292    323   ** (Mem.memType==MEM_Str).
   293    324   */
   294    325   void sqlite3VdbeMemRelease(Mem *p){
          326  +  assert( sqlite3VdbeCheckMemInvariants(p) );
   295    327     VdbeMemRelease(p);
   296    328     if( p->zMalloc ){
   297    329       sqlite3DbFree(p->db, p->zMalloc);
   298    330       p->zMalloc = 0;
   299    331     }
   300    332     p->z = 0;
   301    333     assert( p->xDel==0 );  /* Zeroed by VdbeMemRelease() above */
................................................................................
   625    657   int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
   626    658     int rc = SQLITE_OK;
   627    659   
   628    660     assert( (pFrom->flags & MEM_RowSet)==0 );
   629    661     VdbeMemRelease(pTo);
   630    662     memcpy(pTo, pFrom, MEMCELLSIZE);
   631    663     pTo->flags &= ~MEM_Dyn;
          664  +  pTo->xDel = 0;
   632    665   
   633    666     if( pTo->flags&(MEM_Str|MEM_Blob) ){
   634    667       if( 0==(pFrom->flags&MEM_Static) ){
   635    668         pTo->flags |= MEM_Ephem;
   636    669         rc = sqlite3VdbeMemMakeWriteable(pTo);
   637    670       }
   638    671     }
................................................................................
   750    783     if( nByte>iLimit ){
   751    784       return SQLITE_TOOBIG;
   752    785     }
   753    786   
   754    787     return SQLITE_OK;
   755    788   }
   756    789   
   757         -/*
   758         -** Compare the values contained by the two memory cells, returning
   759         -** negative, zero or positive if pMem1 is less than, equal to, or greater
   760         -** than pMem2. Sorting order is NULL's first, followed by numbers (integers
   761         -** and reals) sorted numerically, followed by text ordered by the collating
   762         -** sequence pColl and finally blob's ordered by memcmp().
   763         -**
   764         -** Two NULL values are considered equal by this function.
   765         -*/
   766         -int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
   767         -  int rc;
   768         -  int f1, f2;
   769         -  int combined_flags;
   770         -
   771         -  f1 = pMem1->flags;
   772         -  f2 = pMem2->flags;
   773         -  combined_flags = f1|f2;
   774         -  assert( (combined_flags & MEM_RowSet)==0 );
   775         - 
   776         -  /* If one value is NULL, it is less than the other. If both values
   777         -  ** are NULL, return 0.
   778         -  */
   779         -  if( combined_flags&MEM_Null ){
   780         -    return (f2&MEM_Null) - (f1&MEM_Null);
   781         -  }
   782         -
   783         -  /* If one value is a number and the other is not, the number is less.
   784         -  ** If both are numbers, compare as reals if one is a real, or as integers
   785         -  ** if both values are integers.
   786         -  */
   787         -  if( combined_flags&(MEM_Int|MEM_Real) ){
   788         -    double r1, r2;
   789         -    if( (f1 & f2 & MEM_Int)!=0 ){
   790         -      if( pMem1->u.i < pMem2->u.i ) return -1;
   791         -      if( pMem1->u.i > pMem2->u.i ) return 1;
   792         -      return 0;
   793         -    }
   794         -    if( (f1&MEM_Real)!=0 ){
   795         -      r1 = pMem1->r;
   796         -    }else if( (f1&MEM_Int)!=0 ){
   797         -      r1 = (double)pMem1->u.i;
   798         -    }else{
   799         -      return 1;
   800         -    }
   801         -    if( (f2&MEM_Real)!=0 ){
   802         -      r2 = pMem2->r;
   803         -    }else if( (f2&MEM_Int)!=0 ){
   804         -      r2 = (double)pMem2->u.i;
   805         -    }else{
   806         -      return -1;
   807         -    }
   808         -    if( r1<r2 ) return -1;
   809         -    if( r1>r2 ) return 1;
   810         -    return 0;
   811         -  }
   812         -
   813         -  /* If one value is a string and the other is a blob, the string is less.
   814         -  ** If both are strings, compare using the collating functions.
   815         -  */
   816         -  if( combined_flags&MEM_Str ){
   817         -    if( (f1 & MEM_Str)==0 ){
   818         -      return 1;
   819         -    }
   820         -    if( (f2 & MEM_Str)==0 ){
   821         -      return -1;
   822         -    }
   823         -
   824         -    assert( pMem1->enc==pMem2->enc );
   825         -    assert( pMem1->enc==SQLITE_UTF8 || 
   826         -            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
   827         -
   828         -    /* The collation sequence must be defined at this point, even if
   829         -    ** the user deletes the collation sequence after the vdbe program is
   830         -    ** compiled (this was not always the case).
   831         -    */
   832         -    assert( !pColl || pColl->xCmp );
   833         -
   834         -    if( pColl ){
   835         -      if( pMem1->enc==pColl->enc ){
   836         -        /* The strings are already in the correct encoding.  Call the
   837         -        ** comparison function directly */
   838         -        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
   839         -      }else{
   840         -        const void *v1, *v2;
   841         -        int n1, n2;
   842         -        Mem c1;
   843         -        Mem c2;
   844         -        memset(&c1, 0, sizeof(c1));
   845         -        memset(&c2, 0, sizeof(c2));
   846         -        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
   847         -        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
   848         -        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
   849         -        n1 = v1==0 ? 0 : c1.n;
   850         -        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
   851         -        n2 = v2==0 ? 0 : c2.n;
   852         -        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
   853         -        sqlite3VdbeMemRelease(&c1);
   854         -        sqlite3VdbeMemRelease(&c2);
   855         -        return rc;
   856         -      }
   857         -    }
   858         -    /* If a NULL pointer was passed as the collate function, fall through
   859         -    ** to the blob case and use memcmp().  */
   860         -  }
   861         - 
   862         -  /* Both values must be blobs.  Compare using memcmp().  */
   863         -  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
   864         -  if( rc==0 ){
   865         -    rc = pMem1->n - pMem2->n;
   866         -  }
   867         -  return rc;
   868         -}
   869         -
   870    790   /*
   871    791   ** Move data out of a btree key or data field and into a Mem structure.
   872    792   ** The data or key is taken from the entry that pCur is currently pointing
   873    793   ** to.  offset and amt determine what portion of the data or key to retrieve.
   874    794   ** key is true to get the key or false to get data.  The result is written
   875    795   ** into the pMem element.
   876    796   **
................................................................................
   903    823     }
   904    824     assert( zData!=0 );
   905    825   
   906    826     if( offset+amt<=available ){
   907    827       sqlite3VdbeMemRelease(pMem);
   908    828       pMem->z = &zData[offset];
   909    829       pMem->flags = MEM_Blob|MEM_Ephem;
          830  +    pMem->n = (int)amt;
   910    831     }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
   911         -    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
   912         -    pMem->enc = 0;
   913         -    pMem->memType = MEM_Blob;
   914    832       if( key ){
   915    833         rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
   916    834       }else{
   917    835         rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
   918    836       }
   919         -    pMem->z[amt] = 0;
   920         -    pMem->z[amt+1] = 0;
   921         -    if( rc!=SQLITE_OK ){
          837  +    if( rc==SQLITE_OK ){
          838  +      pMem->z[amt] = 0;
          839  +      pMem->z[amt+1] = 0;
          840  +      pMem->flags = MEM_Blob|MEM_Term;
          841  +      pMem->memType = MEM_Blob;
          842  +      pMem->n = (int)amt;
          843  +    }else{
   922    844         sqlite3VdbeMemRelease(pMem);
   923    845       }
   924    846     }
   925         -  pMem->n = (int)amt;
   926    847   
   927    848     return rc;
   928    849   }
   929    850   
   930    851   /* This function is only available internally, it is not part of the
   931    852   ** external API. It works in a similar way to sqlite3_value_text(),
   932    853   ** except the data returned is in the encoding specified by the second
................................................................................
  1022    943         nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  1023    944         pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  1024    945         if( pRec ){
  1025    946           pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  1026    947           if( pRec->pKeyInfo ){
  1027    948             assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  1028    949             assert( pRec->pKeyInfo->enc==ENC(db) );
  1029         -          pRec->flags = UNPACKED_PREFIX_MATCH;
  1030    950             pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  1031    951             for(i=0; i<nCol; i++){
  1032    952               pRec->aMem[i].flags = MEM_Null;
  1033    953               pRec->aMem[i].memType = MEM_Null;
  1034    954               pRec->aMem[i].db = db;
  1035    955             }
  1036    956           }else{

Changes to src/vdbesort.c.

   405    405       assert( r2->nField>0 );
   406    406       for(i=0; i<r2->nField; i++){
   407    407         if( r2->aMem[i].flags & MEM_Null ){
   408    408           *pRes = -1;
   409    409           return;
   410    410         }
   411    411       }
   412         -    r2->flags |= UNPACKED_PREFIX_MATCH;
          412  +    assert( r2->default_rc==0 );
   413    413     }
   414    414   
   415         -  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
          415  +  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2, 0);
   416    416   }
   417    417   
   418    418   /*
   419    419   ** This function is called to compare two iterator keys when merging 
   420    420   ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
   421    421   ** value to recalculate.
   422    422   */

Changes to src/wal.c.

  1302   1302     }
  1303   1303   
  1304   1304     if( rc!=SQLITE_OK ){
  1305   1305       walIndexClose(pRet, 0);
  1306   1306       sqlite3OsClose(pRet->pWalFd);
  1307   1307       sqlite3_free(pRet);
  1308   1308     }else{
  1309         -    int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
         1309  +    int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  1310   1310       if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  1311   1311       if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  1312   1312         pRet->padToSectorBoundary = 0;
  1313   1313       }
  1314   1314       *ppWal = pRet;
  1315   1315       WALTRACE(("WAL%d: opened\n", pRet));
  1316   1316     }
................................................................................
  2673   2673       int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  2674   2674       rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  2675   2675       if( rc ) return rc;
  2676   2676       iOffset += iFirstAmt;
  2677   2677       iAmt -= iFirstAmt;
  2678   2678       pContent = (void*)(iFirstAmt + (char*)pContent);
  2679   2679       assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  2680         -    rc = sqlite3OsSync(p->pFd, p->syncFlags);
         2680  +    rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  2681   2681       if( iAmt==0 || rc ) return rc;
  2682   2682     }
  2683   2683     rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  2684   2684     return rc;
  2685   2685   }
  2686   2686   
  2687   2687   /*

Changes to src/where.c.

  1597   1597     Bitmask extraCols;          /* Bitmap of additional columns */
  1598   1598     u8 sentWarning = 0;         /* True if a warnning has been issued */
  1599   1599   
  1600   1600     /* Generate code to skip over the creation and initialization of the
  1601   1601     ** transient index on 2nd and subsequent iterations of the loop. */
  1602   1602     v = pParse->pVdbe;
  1603   1603     assert( v!=0 );
  1604         -  addrInit = sqlite3CodeOnce(pParse);
         1604  +  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  1605   1605   
  1606   1606     /* Count the number of columns that will be added to the index
  1607   1607     ** and used to match WHERE clause constraints */
  1608   1608     nKeyCol = 0;
  1609   1609     pTable = pSrc->pTab;
  1610   1610     pWCEnd = &pWC->a[pWC->nTerm];
  1611   1611     pLoop = pLevel->pWLoop;
................................................................................
  1704   1704     assert( pLevel->iIdxCur>=0 );
  1705   1705     pLevel->iIdxCur = pParse->nTab++;
  1706   1706     sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  1707   1707     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  1708   1708     VdbeComment((v, "for %s", pTable->zName));
  1709   1709   
  1710   1710     /* Fill the automatic index with content */
  1711         -  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
         1711  +  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  1712   1712     regRecord = sqlite3GetTempReg(pParse);
  1713   1713     sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
  1714   1714     sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  1715   1715     sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  1716         -  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
         1716  +  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  1717   1717     sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  1718   1718     sqlite3VdbeJumpHere(v, addrTop);
  1719   1719     sqlite3ReleaseTempReg(pParse, regRecord);
  1720   1720     
  1721   1721     /* Jump here when skipping the initialization */
  1722   1722     sqlite3VdbeJumpHere(v, addrInit);
  1723   1723   }
................................................................................
  1909   1909   #endif
  1910   1910     assert( pRec!=0 );
  1911   1911     iCol = pRec->nField - 1;
  1912   1912     assert( pIdx->nSample>0 );
  1913   1913     assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  1914   1914     do{
  1915   1915       iTest = (iMin+i)/2;
  1916         -    res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
         1916  +    res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec, 0);
  1917   1917       if( res<0 ){
  1918   1918         iMin = iTest+1;
  1919   1919       }else{
  1920   1920         i = iTest;
  1921   1921       }
  1922   1922     }while( res && iMin<i );
  1923   1923   
................................................................................
  1924   1924   #ifdef SQLITE_DEBUG
  1925   1925     /* The following assert statements check that the binary search code
  1926   1926     ** above found the right answer. This block serves no purpose other
  1927   1927     ** than to invoke the asserts.  */
  1928   1928     if( res==0 ){
  1929   1929       /* If (res==0) is true, then sample $i must be equal to pRec */
  1930   1930       assert( i<pIdx->nSample );
  1931         -    assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
         1931  +    assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)
  1932   1932            || pParse->db->mallocFailed );
  1933   1933     }else{
  1934   1934       /* Otherwise, pRec must be smaller than sample $i and larger than
  1935   1935       ** sample ($i-1).  */
  1936   1936       assert( i==pIdx->nSample 
  1937         -         || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
         1937  +         || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec, 0)>0
  1938   1938            || pParse->db->mallocFailed );
  1939   1939       assert( i==0
  1940         -         || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
         1940  +         || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec, 0)<0
  1941   1941            || pParse->db->mallocFailed );
  1942   1942     }
  1943   1943   #endif /* ifdef SQLITE_DEBUG */
  1944   1944   
  1945   1945     /* At this point, aSample[i] is the first sample that is greater than
  1946   1946     ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
  1947   1947     ** than pVal.  If aSample[i]==pVal, then res==0.
................................................................................
  2385   2385       eType = sqlite3FindInIndex(pParse, pX, 0);
  2386   2386       if( eType==IN_INDEX_INDEX_DESC ){
  2387   2387         testcase( bRev );
  2388   2388         bRev = !bRev;
  2389   2389       }
  2390   2390       iTab = pX->iTable;
  2391   2391       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
         2392  +    VdbeCoverageIf(v, bRev);
         2393  +    VdbeCoverageIf(v, !bRev);
  2392   2394       assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  2393   2395       pLoop->wsFlags |= WHERE_IN_ABLE;
  2394   2396       if( pLevel->u.in.nIn==0 ){
  2395   2397         pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  2396   2398       }
  2397   2399       pLevel->u.in.nIn++;
  2398   2400       pLevel->u.in.aInLoop =
................................................................................
  2404   2406         pIn->iCur = iTab;
  2405   2407         if( eType==IN_INDEX_ROWID ){
  2406   2408           pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  2407   2409         }else{
  2408   2410           pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  2409   2411         }
  2410   2412         pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  2411         -      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
         2413  +      sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  2412   2414       }else{
  2413   2415         pLevel->u.in.nIn = 0;
  2414   2416       }
  2415   2417   #endif
  2416   2418     }
  2417   2419     disableTerm(pLevel, pTerm);
  2418   2420     return iReg;
................................................................................
  2499   2501     if( !zAff ){
  2500   2502       pParse->db->mallocFailed = 1;
  2501   2503     }
  2502   2504   
  2503   2505     if( nSkip ){
  2504   2506       int iIdxCur = pLevel->iIdxCur;
  2505   2507       sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
         2508  +    VdbeCoverageIf(v, bRev==0);
         2509  +    VdbeCoverageIf(v, bRev!=0);
  2506   2510       VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  2507   2511       j = sqlite3VdbeAddOp0(v, OP_Goto);
  2508         -    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLt:OP_SeekGt),
         2512  +    pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  2509   2513                               iIdxCur, 0, regBase, nSkip);
         2514  +    VdbeCoverageIf(v, bRev==0);
         2515  +    VdbeCoverageIf(v, bRev!=0);
  2510   2516       sqlite3VdbeJumpHere(v, j);
  2511   2517       for(j=0; j<nSkip; j++){
  2512   2518         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  2513   2519         assert( pIdx->aiColumn[j]>=0 );
  2514   2520         VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
  2515   2521       }
  2516   2522     }    
................................................................................
  2535   2541           sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  2536   2542         }
  2537   2543       }
  2538   2544       testcase( pTerm->eOperator & WO_ISNULL );
  2539   2545       testcase( pTerm->eOperator & WO_IN );
  2540   2546       if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  2541   2547         Expr *pRight = pTerm->pExpr->pRight;
  2542         -      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
         2548  +      if( sqlite3ExprCanBeNull(pRight) ){
         2549  +        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
         2550  +        VdbeCoverage(v);
         2551  +      }
  2543   2552         if( zAff ){
  2544   2553           if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  2545   2554             zAff[j] = SQLITE_AFF_NONE;
  2546   2555           }
  2547   2556           if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  2548   2557             zAff[j] = SQLITE_AFF_NONE;
  2549   2558           }
................................................................................
  2783   2792     }
  2784   2793   
  2785   2794     /* Special case of a FROM clause subquery implemented as a co-routine */
  2786   2795     if( pTabItem->viaCoroutine ){
  2787   2796       int regYield = pTabItem->regReturn;
  2788   2797       sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  2789   2798       pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
         2799  +    VdbeCoverage(v);
  2790   2800       VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  2791   2801       pLevel->op = OP_Goto;
  2792   2802     }else
  2793   2803   
  2794   2804   #ifndef SQLITE_OMIT_VIRTUALTABLE
  2795   2805     if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  2796   2806       /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
................................................................................
  2815   2825         }
  2816   2826       }
  2817   2827       sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  2818   2828       sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  2819   2829       sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  2820   2830                         pLoop->u.vtab.idxStr,
  2821   2831                         pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
         2832  +    VdbeCoverage(v);
  2822   2833       pLoop->u.vtab.needFree = 0;
  2823   2834       for(j=0; j<nConstraint && j<16; j++){
  2824   2835         if( (pLoop->u.vtab.omitMask>>j)&1 ){
  2825   2836           disableTerm(pLevel, pLoop->aLTerm[j]);
  2826   2837         }
  2827   2838       }
  2828   2839       pLevel->op = OP_VNext;
................................................................................
  2838   2849     ){
  2839   2850       /* Case 2:  We can directly reference a single row using an
  2840   2851       **          equality comparison against the ROWID field.  Or
  2841   2852       **          we reference multiple rows using a "rowid IN (...)"
  2842   2853       **          construct.
  2843   2854       */
  2844   2855       assert( pLoop->u.btree.nEq==1 );
  2845         -    iReleaseReg = sqlite3GetTempReg(pParse);
  2846   2856       pTerm = pLoop->aLTerm[0];
  2847   2857       assert( pTerm!=0 );
  2848   2858       assert( pTerm->pExpr!=0 );
  2849   2859       assert( omitTable==0 );
  2850   2860       testcase( pTerm->wtFlags & TERM_VIRTUAL );
         2861  +    iReleaseReg = ++pParse->nMem;
  2851   2862       iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
         2863  +    if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  2852   2864       addrNxt = pLevel->addrNxt;
  2853         -    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
         2865  +    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  2854   2866       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
         2867  +    VdbeCoverage(v);
  2855   2868       sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  2856   2869       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  2857   2870       VdbeComment((v, "pk"));
  2858   2871       pLevel->op = OP_Noop;
  2859   2872     }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  2860   2873            && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  2861   2874     ){
................................................................................
  2881   2894         Expr *pX;             /* The expression that defines the start bound */
  2882   2895         int r1, rTemp;        /* Registers for holding the start boundary */
  2883   2896   
  2884   2897         /* The following constant maps TK_xx codes into corresponding 
  2885   2898         ** seek opcodes.  It depends on a particular ordering of TK_xx
  2886   2899         */
  2887   2900         const u8 aMoveOp[] = {
  2888         -           /* TK_GT */  OP_SeekGt,
  2889         -           /* TK_LE */  OP_SeekLe,
  2890         -           /* TK_LT */  OP_SeekLt,
  2891         -           /* TK_GE */  OP_SeekGe
         2901  +           /* TK_GT */  OP_SeekGT,
         2902  +           /* TK_LE */  OP_SeekLE,
         2903  +           /* TK_LT */  OP_SeekLT,
         2904  +           /* TK_GE */  OP_SeekGE
  2892   2905         };
  2893   2906         assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
  2894   2907         assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
  2895   2908         assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
  2896   2909   
  2897   2910         assert( (pStart->wtFlags & TERM_VNULL)==0 );
  2898   2911         testcase( pStart->wtFlags & TERM_VIRTUAL );
  2899   2912         pX = pStart->pExpr;
  2900   2913         assert( pX!=0 );
  2901   2914         testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  2902   2915         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  2903   2916         sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  2904   2917         VdbeComment((v, "pk"));
         2918  +      VdbeCoverageIf(v, pX->op==TK_GT);
         2919  +      VdbeCoverageIf(v, pX->op==TK_LE);
         2920  +      VdbeCoverageIf(v, pX->op==TK_LT);
         2921  +      VdbeCoverageIf(v, pX->op==TK_GE);
  2905   2922         sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  2906   2923         sqlite3ReleaseTempReg(pParse, rTemp);
  2907   2924         disableTerm(pLevel, pStart);
  2908   2925       }else{
  2909   2926         sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
         2927  +      VdbeCoverageIf(v, bRev==0);
         2928  +      VdbeCoverageIf(v, bRev!=0);
  2910   2929       }
  2911   2930       if( pEnd ){
  2912   2931         Expr *pX;
  2913   2932         pX = pEnd->pExpr;
  2914   2933         assert( pX!=0 );
  2915   2934         assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  2916   2935         testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
................................................................................
  2926   2945       }
  2927   2946       start = sqlite3VdbeCurrentAddr(v);
  2928   2947       pLevel->op = bRev ? OP_Prev : OP_Next;
  2929   2948       pLevel->p1 = iCur;
  2930   2949       pLevel->p2 = start;
  2931   2950       assert( pLevel->p5==0 );
  2932   2951       if( testOp!=OP_Noop ){
  2933         -      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
         2952  +      iRowidReg = ++pParse->nMem;
  2934   2953         sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  2935   2954         sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  2936   2955         sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
         2956  +      VdbeCoverageIf(v, testOp==OP_Le);
         2957  +      VdbeCoverageIf(v, testOp==OP_Lt);
         2958  +      VdbeCoverageIf(v, testOp==OP_Ge);
         2959  +      VdbeCoverageIf(v, testOp==OP_Gt);
  2937   2960         sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  2938   2961       }
  2939   2962     }else if( pLoop->wsFlags & WHERE_INDEXED ){
  2940   2963       /* Case 4: A scan using an index.
  2941   2964       **
  2942   2965       **         The WHERE clause may contain zero or more equality 
  2943   2966       **         terms ("==" or "IN" operators) that refer to the N
................................................................................
  2969   2992       **         to force the output order to conform to an ORDER BY.
  2970   2993       */  
  2971   2994       static const u8 aStartOp[] = {
  2972   2995         0,
  2973   2996         0,
  2974   2997         OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
  2975   2998         OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
  2976         -      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
  2977         -      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
  2978         -      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
  2979         -      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
         2999  +      OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
         3000  +      OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
         3001  +      OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
         3002  +      OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
  2980   3003       };
  2981   3004       static const u8 aEndOp[] = {
  2982         -      OP_Noop,             /* 0: (!end_constraints) */
  2983         -      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
  2984         -      OP_IdxLT             /* 2: (end_constraints && bRev) */
         3005  +      OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
         3006  +      OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
         3007  +      OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
         3008  +      OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
  2985   3009       };
  2986   3010       u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
  2987         -    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
  2988   3011       int regBase;                 /* Base register holding constraint values */
  2989         -    int r1;                      /* Temp register */
  2990   3012       WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
  2991   3013       WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
  2992   3014       int startEq;                 /* True if range start uses ==, >= or <= */
  2993   3015       int endEq;                   /* True if range end uses ==, >= or <= */
  2994   3016       int start_constraints;       /* Start of range is constrained */
  2995   3017       int nConstraint;             /* Number of constraint terms */
  2996   3018       Index *pIdx;                 /* The index we will be using */
  2997   3019       int iIdxCur;                 /* The VDBE cursor for the index */
  2998   3020       int nExtraReg = 0;           /* Number of extra registers needed */
  2999   3021       int op;                      /* Instruction opcode */
  3000   3022       char *zStartAff;             /* Affinity for start of range constraint */
  3001   3023       char cEndAff = 0;            /* Affinity for end of range constraint */
         3024  +    u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
         3025  +    u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
  3002   3026   
  3003   3027       pIdx = pLoop->u.btree.pIndex;
  3004   3028       iIdxCur = pLevel->iIdxCur;
  3005   3029       assert( nEq>=pLoop->u.btree.nSkip );
  3006   3030   
  3007   3031       /* If this loop satisfies a sort order (pOrderBy) request that 
  3008   3032       ** was passed to this function to implement a "SELECT min(x) ..." 
................................................................................
  3013   3037       ** this requires some special handling.
  3014   3038       */
  3015   3039       if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  3016   3040        && (pWInfo->bOBSat!=0)
  3017   3041        && (pIdx->nKeyCol>nEq)
  3018   3042       ){
  3019   3043         assert( pLoop->u.btree.nSkip==0 );
  3020         -      isMinQuery = 1;
         3044  +      bSeekPastNull = 1;
  3021   3045         nExtraReg = 1;
  3022   3046       }
  3023   3047   
  3024   3048       /* Find any inequality constraint terms for the start and end 
  3025   3049       ** of the range. 
  3026   3050       */
  3027   3051       j = nEq;
................................................................................
  3028   3052       if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  3029   3053         pRangeStart = pLoop->aLTerm[j++];
  3030   3054         nExtraReg = 1;
  3031   3055       }
  3032   3056       if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  3033   3057         pRangeEnd = pLoop->aLTerm[j++];
  3034   3058         nExtraReg = 1;
         3059  +      if( pRangeStart==0
         3060  +       && (pRangeEnd->wtFlags & TERM_VNULL)==0
         3061  +       && (j = pIdx->aiColumn[nEq])>=0 
         3062  +       && pIdx->pTable->aCol[j].notNull==0
         3063  +      ){
         3064  +        bSeekPastNull = 1;
         3065  +      }
  3035   3066       }
  3036   3067   
  3037   3068       /* Generate code to evaluate all constraint terms using == or IN
  3038   3069       ** and store the values of those terms in an array of registers
  3039   3070       ** starting at regBase.
  3040   3071       */
  3041   3072       regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
................................................................................
  3047   3078       ** a forward order scan on a descending index, interchange the 
  3048   3079       ** start and end terms (pRangeStart and pRangeEnd).
  3049   3080       */
  3050   3081       if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  3051   3082        || (bRev && pIdx->nKeyCol==nEq)
  3052   3083       ){
  3053   3084         SWAP(WhereTerm *, pRangeEnd, pRangeStart);
         3085  +      SWAP(u8, bSeekPastNull, bStopAtNull);
  3054   3086       }
  3055   3087   
  3056   3088       testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  3057   3089       testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  3058   3090       testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  3059   3091       testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  3060   3092       startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
................................................................................
  3062   3094       start_constraints = pRangeStart || nEq>0;
  3063   3095   
  3064   3096       /* Seek the index cursor to the start of the range. */
  3065   3097       nConstraint = nEq;
  3066   3098       if( pRangeStart ){
  3067   3099         Expr *pRight = pRangeStart->pExpr->pRight;
  3068   3100         sqlite3ExprCode(pParse, pRight, regBase+nEq);
  3069         -      if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  3070         -        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
         3101  +      if( (pRangeStart->wtFlags & TERM_VNULL)==0
         3102  +       && sqlite3ExprCanBeNull(pRight)
         3103  +      ){
         3104  +        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
         3105  +        VdbeCoverage(v);
  3071   3106         }
  3072   3107         if( zStartAff ){
  3073   3108           if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  3074   3109             /* Since the comparison is to be performed with no conversions
  3075   3110             ** applied to the operands, set the affinity to apply to pRight to 
  3076   3111             ** SQLITE_AFF_NONE.  */
  3077   3112             zStartAff[nEq] = SQLITE_AFF_NONE;
................................................................................
  3078   3113           }
  3079   3114           if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  3080   3115             zStartAff[nEq] = SQLITE_AFF_NONE;
  3081   3116           }
  3082   3117         }  
  3083   3118         nConstraint++;
  3084   3119         testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  3085         -    }else if( isMinQuery ){
         3120  +    }else if( bSeekPastNull ){
  3086   3121         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  3087   3122         nConstraint++;
  3088   3123         startEq = 0;
  3089   3124         start_constraints = 1;
  3090   3125       }
  3091         -    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
         3126  +    codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  3092   3127       op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  3093   3128       assert( op!=0 );
  3094         -    testcase( op==OP_Rewind );
  3095         -    testcase( op==OP_Last );
  3096         -    testcase( op==OP_SeekGt );
  3097         -    testcase( op==OP_SeekGe );
  3098         -    testcase( op==OP_SeekLe );
  3099         -    testcase( op==OP_SeekLt );
  3100   3129       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
         3130  +    VdbeCoverage(v);
         3131  +    VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
         3132  +    VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
         3133  +    VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
         3134  +    VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
         3135  +    VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
         3136  +    VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
  3101   3137   
  3102   3138       /* Load the value for the inequality constraint at the end of the
  3103   3139       ** range (if any).
  3104   3140       */
  3105   3141       nConstraint = nEq;
  3106   3142       if( pRangeEnd ){
  3107   3143         Expr *pRight = pRangeEnd->pExpr->pRight;
  3108   3144         sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  3109   3145         sqlite3ExprCode(pParse, pRight, regBase+nEq);
  3110         -      if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  3111         -        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
         3146  +      if( (pRangeEnd->wtFlags & TERM_VNULL)==0
         3147  +       && sqlite3ExprCanBeNull(pRight)
         3148  +      ){
         3149  +        sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
         3150  +        VdbeCoverage(v);
  3112   3151         }
  3113   3152         if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
  3114   3153          && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  3115   3154         ){
  3116   3155           codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  3117   3156         }
  3118   3157         nConstraint++;
  3119   3158         testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
         3159  +    }else if( bStopAtNull ){
         3160  +      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
         3161  +      endEq = 0;
         3162  +      nConstraint++;
  3120   3163       }
  3121   3164       sqlite3DbFree(db, zStartAff);
  3122   3165   
  3123   3166       /* Top of the loop body */
  3124   3167       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  3125   3168   
  3126   3169       /* Check if the index cursor is past the end of the range. */
  3127         -    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  3128         -    testcase( op==OP_Noop );
  3129         -    testcase( op==OP_IdxGE );
  3130         -    testcase( op==OP_IdxLT );
  3131         -    if( op!=OP_Noop ){
         3170  +    if( nConstraint ){
         3171  +      op = aEndOp[bRev*2 + endEq];
  3132   3172         sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  3133         -      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
         3173  +      testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
         3174  +      testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
         3175  +      testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
         3176  +      testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
  3134   3177       }
  3135   3178   
  3136         -    /* If there are inequality constraints, check that the value
  3137         -    ** of the table column that the inequality contrains is not NULL.
  3138         -    ** If it is, jump to the next iteration of the loop.
  3139         -    */
  3140         -    r1 = sqlite3GetTempReg(pParse);
  3141         -    testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
  3142         -    testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
  3143         -    if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 
  3144         -     && (j = pIdx->aiColumn[nEq])>=0 
  3145         -     && pIdx->pTable->aCol[j].notNull==0 
  3146         -     && (nEq || (pLoop->wsFlags & WHERE_BTM_LIMIT)==0)
  3147         -    ){
  3148         -      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  3149         -      VdbeComment((v, "%s", pIdx->pTable->aCol[j].zName));
  3150         -      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  3151         -    }
  3152         -    sqlite3ReleaseTempReg(pParse, r1);
  3153         -
  3154   3179       /* Seek the table cursor, if required */
  3155   3180       disableTerm(pLevel, pRangeStart);
  3156   3181       disableTerm(pLevel, pRangeEnd);
  3157   3182       if( omitTable ){
  3158   3183         /* pIdx is a covering index.  No need to access the main table. */
  3159   3184       }else if( HasRowid(pIdx->pTable) ){
  3160         -      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
         3185  +      iRowidReg = ++pParse->nMem;
  3161   3186         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  3162   3187         sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  3163   3188         sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
  3164   3189       }else{
  3165   3190         Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  3166   3191         iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  3167   3192         for(j=0; j<pPk->nKeyCol; j++){
  3168   3193           k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  3169   3194           sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  3170   3195         }
  3171   3196         sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  3172         -                           iRowidReg, pPk->nKeyCol);
         3197  +                           iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  3173   3198       }
  3174   3199   
  3175   3200       /* Record the instruction used to terminate the loop. Disable 
  3176   3201       ** WHERE clause terms made redundant by the index range scan.
  3177   3202       */
  3178   3203       if( pLoop->wsFlags & WHERE_ONEROW ){
  3179   3204         pLevel->op = OP_Noop;
................................................................................
  3349   3374             if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  3350   3375               int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  3351   3376               int r;
  3352   3377               r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
  3353   3378                                            regRowid, 0);
  3354   3379               sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  3355   3380                                    sqlite3VdbeCurrentAddr(v)+2, r, iSet);
         3381  +            VdbeCoverage(v);
  3356   3382             }
  3357   3383             sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  3358   3384   
  3359   3385             /* The pSubWInfo->untestedTerms flag means that this OR term
  3360   3386             ** contained one or more AND term from a notReady table.  The
  3361   3387             ** terms from the notReady table could not be tested and will
  3362   3388             ** need to be tested later.
................................................................................
  3417   3443         /* Tables marked isRecursive have only a single row that is stored in
  3418   3444         ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
  3419   3445         pLevel->op = OP_Noop;
  3420   3446       }else{
  3421   3447         pLevel->op = aStep[bRev];
  3422   3448         pLevel->p1 = iCur;
  3423   3449         pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
         3450  +      VdbeCoverageIf(v, bRev==0);
         3451  +      VdbeCoverageIf(v, bRev!=0);
  3424   3452         pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  3425   3453       }
  3426   3454     }
  3427   3455   
  3428   3456     /* Insert code to test every subexpression that can be completely
  3429   3457     ** computed using the current set of tables.
  3430   3458     */
................................................................................
  3498   3526           continue;
  3499   3527         }
  3500   3528         assert( pTerm->pExpr );
  3501   3529         sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  3502   3530         pTerm->wtFlags |= TERM_CODED;
  3503   3531       }
  3504   3532     }
  3505         -  sqlite3ReleaseTempReg(pParse, iReleaseReg);
  3506   3533   
  3507   3534     return pLevel->notReady;
  3508   3535   }
  3509   3536   
  3510   3537   #if defined(WHERETRACE_ENABLED) && defined(SQLITE_ENABLE_TREE_EXPLAIN)
  3511   3538   /*
  3512   3539   ** Generate "Explanation" text for a WhereTerm.
................................................................................
  4870   4897       } /* end-if not one-row */
  4871   4898   
  4872   4899       /* Mark off any other ORDER BY terms that reference pLoop */
  4873   4900       if( isOrderDistinct ){
  4874   4901         orderDistinctMask |= pLoop->maskSelf;
  4875   4902         for(i=0; i<nOrderBy; i++){
  4876   4903           Expr *p;
         4904  +        Bitmask mTerm;
  4877   4905           if( MASKBIT(i) & obSat ) continue;
  4878   4906           p = pOrderBy->a[i].pExpr;
  4879         -        if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
         4907  +        mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
         4908  +        if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
         4909  +        if( (mTerm&~orderDistinctMask)==0 ){
  4880   4910             obSat |= MASKBIT(i);
  4881   4911           }
  4882   4912         }
  4883   4913       }
  4884   4914     } /* End the loop over all WhereLoops from outer-most down to inner-most */
  4885   4915     if( obSat==obDone ) return 1;
  4886   4916     if( !isOrderDistinct ) return 0;
................................................................................
  5495   5525     ** and work forward so that the added virtual terms are never processed.
  5496   5526     */
  5497   5527     exprAnalyzeAll(pTabList, &pWInfo->sWC);
  5498   5528     if( db->mallocFailed ){
  5499   5529       goto whereBeginError;
  5500   5530     }
  5501   5531   
  5502         -  /* If the ORDER BY (or GROUP BY) clause contains references to general
  5503         -  ** expressions, then we won't be able to satisfy it using indices, so
  5504         -  ** go ahead and disable it now.
  5505         -  */
  5506         -  if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
  5507         -    for(ii=0; ii<pOrderBy->nExpr; ii++){
  5508         -      Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
  5509         -      if( pExpr->op!=TK_COLUMN ){
  5510         -        pWInfo->pOrderBy = pOrderBy = 0;
  5511         -        break;
  5512         -      }else if( pExpr->iColumn<0 ){
  5513         -        break;
  5514         -      }
  5515         -    }
  5516         -  }
  5517         -
  5518   5532     if( wctrlFlags & WHERE_WANT_DISTINCT ){
  5519   5533       if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  5520   5534         /* The DISTINCT marking is pointless.  Ignore it. */
  5521   5535         pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  5522   5536       }else if( pOrderBy==0 ){
  5523   5537         /* Try to ORDER BY the result set to make distinct processing easier */
  5524   5538         pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
................................................................................
  5786   5800       int addr;
  5787   5801       pLevel = &pWInfo->a[i];
  5788   5802       pLoop = pLevel->pWLoop;
  5789   5803       sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  5790   5804       if( pLevel->op!=OP_Noop ){
  5791   5805         sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  5792   5806         sqlite3VdbeChangeP5(v, pLevel->p5);
         5807  +      VdbeCoverage(v);
         5808  +      VdbeCoverageIf(v, pLevel->op==OP_Next);
         5809  +      VdbeCoverageIf(v, pLevel->op==OP_Prev);
         5810  +      VdbeCoverageIf(v, pLevel->op==OP_VNext);
  5793   5811       }
  5794   5812       if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  5795   5813         struct InLoop *pIn;
  5796   5814         int j;
  5797   5815         sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  5798   5816         for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  5799   5817           sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  5800   5818           sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
         5819  +        VdbeCoverage(v);
         5820  +        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
         5821  +        VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  5801   5822           sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  5802   5823         }
  5803   5824         sqlite3DbFree(db, pLevel->u.in.aInLoop);
  5804   5825       }
  5805   5826       sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  5806   5827       if( pLevel->addrSkip ){
  5807   5828         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
  5808   5829         VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  5809   5830         sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  5810   5831         sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  5811   5832       }
  5812   5833       if( pLevel->iLeftJoin ){
  5813         -      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
         5834  +      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  5814   5835         assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  5815   5836              || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  5816   5837         if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  5817   5838           sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  5818   5839         }
  5819   5840         if( pLoop->wsFlags & WHERE_INDEXED ){
  5820   5841           sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
................................................................................
  5845   5866       assert( pTab!=0 );
  5846   5867       pLoop = pLevel->pWLoop;
  5847   5868   
  5848   5869       /* For a co-routine, change all OP_Column references to the table of
  5849   5870       ** the co-routine into OP_SCopy of result contained in a register.
  5850   5871       ** OP_Rowid becomes OP_Null.
  5851   5872       */
  5852         -    if( pTabItem->viaCoroutine ){
         5873  +    if( pTabItem->viaCoroutine && !db->mallocFailed ){
  5853   5874         last = sqlite3VdbeCurrentAddr(v);
  5854   5875         k = pLevel->addrBody;
  5855   5876         pOp = sqlite3VdbeGetOp(v, k);
  5856   5877         for(; k<last; k++, pOp++){
  5857   5878           if( pOp->p1!=pLevel->iTabCur ) continue;
  5858   5879           if( pOp->opcode==OP_Column ){
  5859   5880             pOp->opcode = OP_SCopy;

Changes to test/analyze9.test.

   322    322   #-------------------------------------------------------------------------
   323    323   # The following tests experiment with adding corrupted records to the
   324    324   # 'sample' column of the sqlite_stat4 table.
   325    325   #
   326    326   reset_db
   327    327   sqlite3_db_config_lookaside db 0 0 0
   328    328   
          329  +database_may_be_corrupt
   329    330   do_execsql_test 7.1 {
   330    331     CREATE TABLE t1(a, b);
   331    332     CREATE INDEX i1 ON t1(a, b);
   332    333     INSERT INTO t1 VALUES(1, 1);
   333    334     INSERT INTO t1 VALUES(2, 2);
   334    335     INSERT INTO t1 VALUES(3, 3);
   335    336     INSERT INTO t1 VALUES(4, 4);
................................................................................
   361    362   
   362    363   do_execsql_test 7.5 {
   363    364     ANALYZE;
   364    365     UPDATE sqlite_stat4 SET nlt = '0 0 0';
   365    366     ANALYZE sqlite_master;
   366    367     SELECT * FROM t1 WHERE a = 5;
   367    368   } {5 5}
          369  +
          370  +database_never_corrupt
   368    371   
   369    372   #-------------------------------------------------------------------------
   370    373   #
   371    374   reset_db
   372    375   do_execsql_test 8.1 {
   373    376     CREATE TABLE t1(x TEXT);
   374    377     CREATE INDEX i1 ON t1(x);

Changes to test/capi3e.test.

    16     16   
    17     17   set testdir [file dirname $argv0]
    18     18   source $testdir/tester.tcl
    19     19   
    20     20   # Make sure the system encoding is utf-8. Otherwise, if the system encoding
    21     21   # is other than utf-8, [file isfile $x] may not refer to the same file
    22     22   # as [sqlite3 db $x].
    23         -encoding system utf-8
           23  +#
           24  +# This is no longer needed here because it should be done within the test
           25  +# fixture executable itself, via Tcl_SetSystemEncoding.
           26  +#
           27  +# encoding system utf-8
    24     28   
    25     29   # Do not use a codec for tests in this file, as the database file is
    26     30   # manipulated directly using tcl scripts (using the [hexio_write] command).
    27     31   #
    28     32   do_not_use_codec
    29     33   
    30     34   # Return the UTF-16 representation of the supplied UTF-8 string $str.

Changes to test/corruptG.test.

    72     72       SELECT rowid FROM t1 WHERE a='abc' and b='xyz123456789XYZ';
    73     73     }
    74     74     # The following test result is brittle.  The point above is to try to
    75     75     # force a buffer overread by a corrupt database file.  If we get an
    76     76     # incorrect answer from a corrupt database file, that is OK.  If the
    77     77     # result below changes, that just means that "undefined behavior" has
    78     78     # changed.
    79         -} {0 52}
           79  +} {/0 .*/}
    80     80   
    81     81   finish_test

Added test/corruptI.test.

            1  +# 2014-01-20
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +#
           12  +
           13  +set testdir [file dirname $argv0]
           14  +source $testdir/tester.tcl
           15  +set testprefix corruptI
           16  +
           17  +# Do not use a codec for tests in this file, as the database file is
           18  +# manipulated directly using tcl scripts (using the [hexio_write] command).
           19  +#
           20  +do_not_use_codec
           21  +database_may_be_corrupt
           22  +
           23  +# Initialize the database.
           24  +#
           25  +do_execsql_test 1.1 {
           26  +  PRAGMA page_size=1024;
           27  +  PRAGMA auto_vacuum=0;
           28  +  CREATE TABLE t1(a);
           29  +  CREATE INDEX i1 ON t1(a);
           30  +  INSERT INTO t1 VALUES('a');
           31  +} {}
           32  +db close
           33  +
           34  +do_test 1.2 {
           35  +  set offset [hexio_get_int [hexio_read test.db [expr 2*1024 + 8] 2]]
           36  +  set off [expr 2*1024 + $offset + 1]
           37  +  hexio_write test.db $off FF06
           38  +
           39  +  breakpoint
           40  +
           41  +  sqlite3 db test.db
           42  +  catchsql { SELECT * FROM t1 WHERE a = 10 }
           43  +} {1 {database disk image is malformed}}
           44  +
           45  +
           46  +finish_test
           47  +

Changes to test/insert.test.

   394    394         CREATE TABLE t10(a,b,c);
   395    395         INSERT INTO t10 VALUES(1,2,3), (4,5,6), (7,8,9);
   396    396         SELECT * FROM t10;
   397    397       }
   398    398     } {1 2 3 4 5 6 7 8 9}
   399    399     do_test insert-10.2 {
   400    400       catchsql {
   401         -      INSERT INTO t10 VALUES(11,12,13), (14,15);
          401  +      INSERT INTO t10 VALUES(11,12,13), (14,15), (16,17,28);
   402    402       }
   403    403     } {1 {all VALUES must have the same number of terms}}
   404    404   }
          405  +
          406  +# Need for the OP_SoftNull opcode
          407  +#
          408  +do_execsql_test insert-11.1 {
          409  +  CREATE TABLE t11a AS SELECT '123456789' AS x;
          410  +  CREATE TABLE t11b (a INTEGER PRIMARY KEY, b, c);
          411  +  INSERT INTO t11b SELECT x, x, x FROM t11a;
          412  +  SELECT quote(a), quote(b), quote(c) FROM t11b;
          413  +} {123456789 '123456789' '123456789'}
          414  +
   405    415   
   406    416   integrity_check insert-99.0
   407    417   
   408    418   finish_test

Changes to test/insert4.test.

   249    249     } {}
   250    250   }
   251    251   
   252    252   # Check some error conditions:
   253    253   #
   254    254   do_test insert4-5.1 {
   255    255     # Table does not exist.
   256         -  catchsql { INSERT INTO t2 SELECT * FROM nosuchtable }
          256  +  catchsql { INSERT INTO t2 SELECT a, b FROM nosuchtable }
   257    257   } {1 {no such table: nosuchtable}}
   258    258   do_test insert4-5.2 {
   259    259     # Number of columns does not match.
   260    260     catchsql { 
   261    261       CREATE TABLE t5(a, b, c);
   262    262       INSERT INTO t4 SELECT * FROM t5;
   263    263     }

Changes to test/loadext.test.

    61     61   set dlerror_nosymbol   {%s: undefined symbol: %s}
    62     62   
    63     63   if {$::tcl_platform(os) eq "Darwin"} {
    64     64     set dlerror_nosuchfile {dlopen(%s, 10): image not found}
    65     65     set dlerror_notadll    {dlopen(%1$s, 10): no suitable image found.*}
    66     66     set dlerror_nosymbol   {dlsym(XXX, %2$s): symbol not found}
    67     67   }
           68  +
           69  +if {$::tcl_platform(platform) eq "windows"} {
           70  +  set dlerror_nosuchfile {The specified module could not be found.*}
           71  +  set dlerror_notadll    {%%1 is not a valid Win32 application.*}
           72  +  set dlerror_nosymbol   {The specified procedure could not be found.*}
           73  +}
    68     74   
    69     75   # Make sure the test extension actually exists.  If it does not
    70     76   # exist, try to create it.  If unable to create it, then skip this
    71     77   # test file.
    72     78   #
    73     79   if {![file exists $testextension]} {
    74     80     set srcdir [file dir $testdir]/src
................................................................................
   163    169     set rc [catch {
   164    170       sqlite3_load_extension db $testextension icecream
   165    171     } msg]
   166    172     if {$::tcl_platform(os) eq "Darwin"} {
   167    173       regsub {0x[1234567890abcdefABCDEF]*} $msg XXX msg
   168    174     }
   169    175     list $rc $msg
   170         -} [list 1 [format $dlerror_nosymbol $testextension icecream]]
          176  +} /[list 1 [format $dlerror_nosymbol $testextension icecream]]/
   171    177   
   172    178   # Try to load an extension for which the entry point fails (returns non-zero) 
   173    179   #
   174    180   do_test loadext-2.4 {
   175    181     set rc [catch {
   176    182       sqlite3_load_extension db $testextension testbrokenext_init
   177    183     } msg]
................................................................................
   263    269   # Malloc failure in sqlite3_auto_extension and sqlite3_load_extension
   264    270   #
   265    271   do_malloc_test loadext-5 -tclprep {
   266    272     sqlite3_reset_auto_extension
   267    273   } -tclbody {
   268    274     if {[autoinstall_test_functions]==7} {error "out of memory"}
   269    275   }
   270         -do_malloc_test loadext-6 -tclbody {
   271         -  db enable_load_extension 1
   272         -  sqlite3_load_extension db $::testextension testloadext_init
          276  +
          277  +# On Windows, this malloc test must be skipped because the winDlOpen
          278  +# function itself can fail due to "out of memory" conditions.
          279  +#
          280  +if {$::tcl_platform(platform) ne "windows"} {
          281  +  do_malloc_test loadext-6 -tclbody {
          282  +    db enable_load_extension 1
          283  +    sqlite3_load_extension db $::testextension testloadext_init
          284  +  }
   273    285   }
          286  +
   274    287   autoinstall_test_functions
   275    288   
   276    289   finish_test

Changes to test/pragma.test.

  1571   1571   do_test pragma-20.8 {
  1572   1572     catchsql {PRAGMA data_store_directory}
  1573   1573   } {0 {}}
  1574   1574   
  1575   1575   forcedelete data_dir
  1576   1576   } ;# endif windows
  1577   1577   
         1578  +database_may_be_corrupt
         1579  +
  1578   1580   do_test 21.1 {
  1579   1581     # Create a corrupt database in testerr.db. And a non-corrupt at test.db.
  1580   1582     #
  1581   1583     db close
  1582   1584     forcedelete test.db
  1583   1585     sqlite3 db test.db
  1584   1586     execsql { 
................................................................................
  1596   1598   } {100}
  1597   1599   
  1598   1600   set mainerr {*** in database main ***
  1599   1601   Multiple uses for byte 672 of page 15}
  1600   1602   set auxerr {*** in database aux ***
  1601   1603   Multiple uses for byte 672 of page 15}
  1602   1604   
         1605  +set mainerr {/{\*\*\* in database main \*\*\*
         1606  +Multiple uses for byte 672 of page 15}.*/}
         1607  +set auxerr {/{\*\*\* in database aux \*\*\*
         1608  +Multiple uses for byte 672 of page 15}.*/}
         1609  +
  1603   1610   do_test 22.2 {
  1604   1611     catch { db close }
  1605   1612     sqlite3 db testerr.db
  1606   1613     execsql { PRAGMA integrity_check }
  1607         -} [list $mainerr]
         1614  +} $mainerr
  1608   1615   
  1609   1616   do_test 22.3.1 {
  1610   1617     catch { db close }
  1611   1618     sqlite3 db test.db
  1612   1619     execsql { 
  1613   1620       ATTACH 'testerr.db' AS 'aux';
  1614   1621       PRAGMA integrity_check;
  1615   1622     }
  1616         -} [list $auxerr]
         1623  +} $auxerr
  1617   1624   do_test 22.3.2 {
  1618   1625     execsql { PRAGMA main.integrity_check; }
  1619   1626   } {ok}
  1620   1627   do_test 22.3.3 {
  1621   1628     execsql { PRAGMA aux.integrity_check; }
  1622         -} [list $auxerr]
         1629  +} $auxerr
  1623   1630   
  1624   1631   do_test 22.4.1 {
  1625   1632     catch { db close }
  1626   1633     sqlite3 db testerr.db
  1627   1634     execsql { 
  1628   1635       ATTACH 'test.db' AS 'aux';
  1629   1636       PRAGMA integrity_check;
  1630   1637     }
  1631         -} [list $mainerr]
         1638  +} $mainerr
  1632   1639   do_test 22.4.2 {
  1633   1640     execsql { PRAGMA main.integrity_check; }
  1634         -} [list $mainerr]
         1641  +} $mainerr
  1635   1642   do_test 22.4.3 {
  1636   1643     execsql { PRAGMA aux.integrity_check; }
  1637   1644   } {ok}
  1638   1645   
  1639   1646   db close
  1640   1647   forcedelete test.db test.db-wal test.db-journal
  1641   1648   sqlite3 db test.db
................................................................................
  1676   1683       CREATE TABLE t2(x, y INTEGER REFERENCES t1);
  1677   1684     }
  1678   1685     db2 eval {
  1679   1686       PRAGMA foreign_key_list(t2);
  1680   1687     }
  1681   1688   } {0 0 t1 y {} {NO ACTION} {NO ACTION} NONE}
  1682   1689   
         1690  +database_never_corrupt
  1683   1691   finish_test

Changes to test/select4.test.

   819    819       INSERT INTO t13 VALUES(2,2);
   820    820       INSERT INTO t13 VALUES(3,2);
   821    821       INSERT INTO t13 VALUES(4,2);
   822    822       CREATE INDEX t13ab ON t13(a,b);
   823    823       SELECT DISTINCT b from t13 WHERE a IN (1,2,3);
   824    824     }
   825    825   } {1 2}
          826  +
          827  +# 2014-02-18: Make sure compound SELECTs work with VALUES clauses
          828  +#
          829  +do_execsql_test select4-14.1 {
          830  +  CREATE TABLE t14(a,b,c);
          831  +  INSERT INTO t14 VALUES(1,2,3),(4,5,6);
          832  +  SELECT * FROM t14 INTERSECT VALUES(3,2,1),(2,3,1),(1,2,3),(2,1,3);
          833  +} {1 2 3}
          834  +do_execsql_test select4-14.2 {
          835  +  SELECT * FROM t14 INTERSECT VALUES(1,2,3);
          836  +} {1 2 3}
          837  +do_execsql_test select4-14.3 {
          838  +  SELECT * FROM t14
          839  +   UNION VALUES(3,2,1),(2,3,1),(1,2,3),(7,8,9),(4,5,6)
          840  +   UNION SELECT * FROM t14 ORDER BY 1, 2, 3
          841  +} {1 2 3 2 3 1 3 2 1 4 5 6 7 8 9}
          842  +do_execsql_test select4-14.4 {
          843  +  SELECT * FROM t14
          844  +   UNION VALUES(3,2,1)
          845  +   UNION SELECT * FROM t14 ORDER BY 1, 2, 3
          846  +} {1 2 3 3 2 1 4 5 6}
          847  +do_execsql_test select4-14.5 {
          848  +  SELECT * FROM t14 EXCEPT VALUES(3,2,1),(2,3,1),(1,2,3),(2,1,3);
          849  +} {4 5 6}
          850  +do_execsql_test select4-14.6 {
          851  +  SELECT * FROM t14 EXCEPT VALUES(1,2,3)
          852  +} {4 5 6}
          853  +do_execsql_test select4-14.7 {
          854  +  SELECT * FROM t14 EXCEPT VALUES(1,2,3) EXCEPT VALUES(4,5,6)
          855  +} {}
          856  +do_execsql_test select4-14.8 {
          857  +  SELECT * FROM t14 EXCEPT VALUES('a','b','c') EXCEPT VALUES(4,5,6)
          858  +} {1 2 3}
          859  +do_execsql_test select4-14.9 {
          860  +  SELECT * FROM t14 UNION ALL VALUES(3,2,1),(2,3,1),(1,2,3),(2,1,3);
          861  +} {1 2 3 4 5 6 3 2 1 2 3 1 1 2 3 2 1 3}
   826    862   
   827    863   finish_test

Added test/selectF.test.

            1  +# 2014-03-03
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +#
           12  +# This file verifies that an OP_Copy operation is used instead of OP_SCopy
           13  +# in a compound select in a case where the source register might be changed
           14  +# before the copy is used.
           15  +#
           16  +
           17  +set testdir [file dirname $argv0]
           18  +source $testdir/tester.tcl
           19  +set testprefix selectF
           20  +
           21  +do_execsql_test 1 {
           22  +  BEGIN TRANSACTION;
           23  +  CREATE TABLE t1(a, b, c);
           24  +  INSERT INTO "t1" VALUES(1,'one','I');
           25  +  CREATE TABLE t2(d, e, f);
           26  +  INSERT INTO "t2" VALUES(5,'ten','XX');
           27  +  INSERT INTO "t2" VALUES(6,NULL,NULL);
           28  +
           29  +  CREATE INDEX i1 ON t1(b, a);
           30  +  COMMIT;
           31  +}
           32  +
           33  +#explain_i {
           34  +#  SELECT * FROM t2
           35  +#  UNION ALL 
           36  +#  SELECT * FROM t1 WHERE a<5 
           37  +#  ORDER BY 2, 1
           38  +#}
           39  +
           40  +do_execsql_test 2 {
           41  +  SELECT * FROM t2
           42  +  UNION ALL 
           43  +  SELECT * FROM t1 WHERE a<5 
           44  +  ORDER BY 2, 1
           45  +} {6 {} {} 1 one I 5 ten XX}
           46  +
           47  +
           48  +  
           49  +finish_test

Changes to test/shell5.test.

   280    280     catchcmd test.db {.mode csv
   281    281       CREATE TABLE t1(a,b,c,d);
   282    282   .import shell5.csv t1
   283    283     }
   284    284     sqlite3 db test.db
   285    285     db eval {SELECT hex(c) FROM t1 ORDER BY rowid}
   286    286   } {636F6C756D6E33 783320220D0A64617461222033 783320220A64617461222033}
          287  +
          288  +# Blank last column with \r\n line endings.
          289  +do_test shell5-1.11 {
          290  +  set out [open shell5.csv w]
          291  +  fconfigure $out -translation binary
          292  +  puts $out "column1,column2,column3\r"
          293  +  puts $out "a,b, \r"
          294  +  puts $out "x,y,\r"
          295  +  puts $out "p,q,r\r"
          296  +  close $out
          297  +  catch {db close}
          298  +  forcedelete test.db
          299  +  catchcmd test.db {.mode csv
          300  +.import shell5.csv t1
          301  +  }
          302  +  sqlite3 db test.db
          303  +  db eval {SELECT *, '|' FROM t1}
          304  +} {a b { } | x y {} | p q r |}
          305  +
   287    306   
   288    307   db close
   289    308   
   290    309   finish_test

Changes to test/tester.tcl.

  1064   1064   
  1065   1065     # Set up colors for the different opcodes. Scheme is as follows:
  1066   1066     #
  1067   1067     #   Red:   Opcodes that write to a b-tree.
  1068   1068     #   Blue:  Opcodes that reposition or seek a cursor. 
  1069   1069     #   Green: The ResultRow opcode.
  1070   1070     #
  1071         -  set R "\033\[31;1m"        ;# Red fg
  1072         -  set G "\033\[32;1m"        ;# Green fg
  1073         -  set B "\033\[34;1m"        ;# Red fg
  1074         -  set D "\033\[39;0m"        ;# Default fg
         1071  +  if { [catch {fconfigure stdout -mode}]==0 } {
         1072  +    set R "\033\[31;1m"        ;# Red fg
         1073  +    set G "\033\[32;1m"        ;# Green fg
         1074  +    set B "\033\[34;1m"        ;# Red fg
         1075  +    set D "\033\[39;0m"        ;# Default fg
         1076  +  } else {
         1077  +    set R ""
         1078  +    set G ""
         1079  +    set B ""
         1080  +    set D ""
         1081  +  }
  1075   1082     foreach opcode {
  1076   1083         Seek SeekGe SeekGt SeekLe SeekLt NotFound Last Rewind
  1077   1084         NoConflict Next Prev VNext VPrev VFilter
  1078   1085     } {
  1079   1086       set color($opcode) $B
  1080   1087     }
  1081   1088     foreach opcode {ResultRow} {

Added test/tkt-4ef7e3cfca.test.

            1  +# 2014-03-04
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +#
           12  +# This file implements tests to verify that ticket [4ef7e3cfca] has been
           13  +# fixed.
           14  +#
           15  +
           16  +set testdir [file dirname $argv0]
           17  +source $testdir/tester.tcl
           18  +set testprefix tkt-4ef7e3cfca
           19  +
           20  +do_catchsql_test 1.1 {
           21  +  CREATE TABLE x(a);
           22  +  CREATE TRIGGER t AFTER INSERT ON x BEGIN
           23  +    SELECT * FROM x WHERE abc.a = 1;
           24  +  END;
           25  +  INSERT INTO x VALUES('assert');
           26  +} {1 {no such column: abc.a}}
           27  +
           28  +reset_db
           29  +do_execsql_test 2.1 {
           30  +  CREATE TABLE w(a);
           31  +  CREATE TABLE x(a);
           32  +  CREATE TABLE y(a);
           33  +  CREATE TABLE z(a);
           34  +
           35  +  INSERT INTO x(a) VALUES(5);
           36  +  INSERT INTO y(a) VALUES(10);
           37  +
           38  +  CREATE TRIGGER t AFTER INSERT ON w BEGIN
           39  +    INSERT INTO z
           40  +    SELECT (SELECT x.a + y.a FROM y) FROM x;
           41  +  END;
           42  +  INSERT INTO w VALUES('incorrect');
           43  +}
           44  +do_execsql_test 2.2 {
           45  +  SELECT * FROM z;
           46  +} {15}
           47  +
           48  +reset_db
           49  +do_execsql_test 3.1 {
           50  +  CREATE TABLE w(a);
           51  +  CREATE TABLE x(b);
           52  +  CREATE TABLE y(a);
           53  +  CREATE TABLE z(a);
           54  +
           55  +  INSERT INTO x(b) VALUES(5);
           56  +  INSERT INTO y(a) VALUES(10);
           57  +
           58  +  CREATE TRIGGER t AFTER INSERT ON w BEGIN
           59  +    INSERT INTO z
           60  +    SELECT (SELECT x.b + y.a FROM y) FROM x;
           61  +  END;
           62  +  INSERT INTO w VALUES('assert');
           63  +}
           64  +do_execsql_test 3.2 {
           65  +  SELECT * FROM z;
           66  +} {15}
           67  +
           68  +finish_test

Added test/tkt-8c63ff0ec.test.

            1  +# 2014-02-25
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +# 
           12  +# Test cases to show that ticket [8c63ff0eca81a9132d8d67b31cd6ae9712a2cc6f]
           13  +# "Incorrect query result on a UNION ALL" which was caused by using the same
           14  +# temporary register in concurrent co-routines, as been fixed.
           15  +# 
           16  +
           17  +
           18  +set testdir [file dirname $argv0]
           19  +source $testdir/tester.tcl
           20  +set ::testprefix tkt-8c63ff0ec
           21  +
           22  +do_execsql_test 1.1 {
           23  +  CREATE TABLE t1(a INTEGER PRIMARY KEY, b, c, d, e);
           24  +  INSERT INTO t1 VALUES(1,20,30,40,50),(3,60,70,80,90);
           25  +  CREATE TABLE t2(x INTEGER PRIMARY KEY);
           26  +  INSERT INTO t2 VALUES(2);
           27  +  CREATE TABLE t3(z);
           28  +  INSERT INTO t3 VALUES(2),(2),(2),(2);
           29  +  
           30  +  SELECT a, b+c FROM t1
           31  +  UNION ALL
           32  +  SELECT x, 5 FROM t2 JOIN t3 ON z=x WHERE x=2
           33  +  ORDER BY a;
           34  +} {1 50 2 5 2 5 2 5 2 5 3 130}
           35  +do_execsql_test 1.2 {
           36  +  SELECT a, b+c+d FROM t1
           37  +  UNION ALL
           38  +  SELECT x, 5 FROM t2 JOIN t3 ON z=x WHERE x=2
           39  +  ORDER BY a;
           40  +} {1 90 2 5 2 5 2 5 2 5 3 210}
           41  +do_execsql_test 1.3 {
           42  +  SELECT a, b+c+d+e FROM t1
           43  +  UNION ALL
           44  +  SELECT x, 5 FROM t2 JOIN t3 ON z=x WHERE x=2
           45  +  ORDER BY a;
           46  +} {1 140 2 5 2 5 2 5 2 5 3 300}
           47  +
           48  +finish_test

Changes to test/unixexcl.test.

   105    105         sql2 { 
   106    106           BEGIN;
   107    107             SELECT * FROM t1;
   108    108         }
   109    109       } {1 2}
   110    110       do_test unixexcl-3.$tn.3 {
   111    111         sql1 { PRAGMA wal_checkpoint; INSERT INTO t1 VALUES(3, 4); }
   112         -    } {0 3 3}
          112  +    } {0 5 5}
   113    113       do_test unixexcl-3.$tn.4 {
   114    114         sql2 { SELECT * FROM t1; }
   115    115       } {1 2}
   116    116       do_test unixexcl-3.$tn.5 {
   117    117         sql1 { SELECT * FROM t1; }
   118    118       } {1 2 3 4}
   119    119       do_test unixexcl-3.$tn.6 {
   120    120         sql2 { COMMIT; SELECT * FROM t1; }
   121    121       } {1 2 3 4}
   122    122       do_test unixexcl-3.$tn.7 {
   123    123         sql1 { PRAGMA wal_checkpoint; }
   124         -    } {0 4 4}
          124  +    } {0 7 7}
   125    125     }
   126    126   }
   127    127   
   128    128   finish_test

Changes to test/walro.test.

    28     28   #
    29     29   ifcapable !wal {
    30     30     finish_test
    31     31     return
    32     32   }
    33     33   
    34     34   do_multiclient_test tn {
    35         -  # Do not run tests with the connections in the same process.
    36         -  #
    37         -  if {$tn==2} continue
    38     35     
    39     36     # Close all connections and delete the database.
    40     37     #
    41     38     code1 { db close  }
    42     39     code2 { db2 close }
    43     40     code3 { db3 close }
    44     41     forcedelete test.db
    45     42     forcedelete walro
           43  +  
           44  +  # Do not run tests with the connections in the same process.
           45  +  #
           46  +  if {$tn==2} continue
    46     47   
    47     48     foreach c {code1 code2 code3} {
    48     49       $c {
    49     50         sqlite3_shutdown
    50     51         sqlite3_config_uri 1
    51     52       }
    52     53     }
................................................................................
   228    229   forcedelete test.db
   229    230   
   230    231   #-----------------------------------------------------------------------
   231    232   # Test cases 2.* check that a read-only connection may read the
   232    233   # database file while a checkpoint operation is ongoing.
   233    234   #
   234    235   do_multiclient_test tn {
   235         -  # Do not run tests with the connections in the same process.
   236         -  #
   237         -  if {$tn==2} continue
   238    236     
   239    237     # Close all connections and delete the database.
   240    238     #
   241    239     code1 { db close  }
   242    240     code2 { db2 close }
   243    241     code3 { db3 close }
   244    242     forcedelete test.db
   245    243     forcedelete walro
          244  +  
          245  +  # Do not run tests with the connections in the same process.
          246  +  #
          247  +  if {$tn==2} continue
   246    248   
   247    249     foreach c {code1 code2 code3} {
   248    250       $c {
   249    251         sqlite3_shutdown
   250    252         sqlite3_config_uri 1
   251    253       }
   252    254     }

Changes to test/where.test.

   233    233     count {SELECT w FROM t1 WHERE w==97 AND w==97}
   234    234   } {97 2}
   235    235   do_test where-1.34 {
   236    236     count {SELECT w FROM t1 WHERE w+1==98}
   237    237   } {97 99}
   238    238   do_test where-1.35 {
   239    239     count {SELECT w FROM t1 WHERE w<3}
   240         -} {1 2 2}
          240  +} {1 2 3}
   241    241   do_test where-1.36 {
   242    242     count {SELECT w FROM t1 WHERE w<=3}
   243         -} {1 2 3 3}
          243  +} {1 2 3 4}
   244    244   do_test where-1.37 {
   245    245     count {SELECT w FROM t1 WHERE w+1<=4 ORDER BY w}
   246    246   } {1 2 3 99}
   247    247   
   248    248   do_test where-1.38 {
   249    249     count {SELECT (w) FROM t1 WHERE (w)>(97)}
   250    250   } {98 99 100 3}

Changes to test/where2.test.

   116    116     }
   117    117   } {85 6 7396 7402 sort t1 i1xy}
   118    118   do_test where2-2.3 {
   119    119     queryplan {
   120    120       SELECT * FROM t1 WHERE rowid=85 AND x=6 AND y=7396 ORDER BY random();
   121    121     }
   122    122   } {85 6 7396 7402 nosort t1 *}
          123  +
          124  +# Ticket [65bdeb9739605cc22966f49208452996ff29a640] 2014-02-26
          125  +# Make sure "ORDER BY random" does not gets optimized out.
          126  +#
          127  +do_test where2-2.4 {
          128  +  db eval {
          129  +    CREATE TABLE x1(a INTEGER PRIMARY KEY, b DEFAULT 1);
          130  +    WITH RECURSIVE
          131  +       cnt(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM cnt WHERE x<50)
          132  +    INSERT INTO x1 SELECT x, 1 FROM cnt;
          133  +    CREATE TABLE x2(x INTEGER PRIMARY KEY);
          134  +    INSERT INTO x2 VALUES(1);
          135  +  }
          136  +  set sql {SELECT * FROM x1, x2 WHERE x=1 ORDER BY random()}
          137  +  set out1 [db eval $sql]
          138  +  set out2 [db eval $sql]
          139  +  set out3 [db eval $sql]
          140  +  expr {$out1!=$out2 && $out2!=$out3}
          141  +} {1}
          142  +do_execsql_test where2-2.5 {
          143  +  -- random() is not optimized out
          144  +  EXPLAIN SELECT * FROM x1, x2 WHERE x=1 ORDER BY random();
          145  +} {/ random/}
          146  +do_execsql_test where2-2.5b {
          147  +  -- random() is not optimized out
          148  +  EXPLAIN SELECT * FROM x1, x2 WHERE x=1 ORDER BY random();
          149  +} {/ SorterOpen /}
          150  +do_execsql_test where2-2.6 {
          151  +  -- other constant functions are optimized out
          152  +  EXPLAIN SELECT * FROM x1, x2 WHERE x=1 ORDER BY abs(5);
          153  +} {~/ abs/}
          154  +do_execsql_test where2-2.6b {
          155  +  -- other constant functions are optimized out
          156  +  EXPLAIN SELECT * FROM x1, x2 WHERE x=1 ORDER BY abs(5);
          157  +} {~/ SorterOpen /}
          158  +
   123    159   
   124    160   
   125    161   # Efficient handling of forward and reverse table scans.
   126    162   #
   127    163   do_test where2-3.1 {
   128    164     queryplan {
   129    165       SELECT * FROM t1 ORDER BY rowid LIMIT 2

Changes to test/where4.test.

    67     67     count {SELECT rowid FROM t1 WHERE w=1 AND +x IS NULL}
    68     68   } {2 3}
    69     69   do_test where4-1.5 {
    70     70     count {SELECT rowid FROM t1 WHERE w=1 AND x>0}
    71     71   } {1 2}
    72     72   do_test where4-1.6 {
    73     73     count {SELECT rowid FROM t1 WHERE w=1 AND x<9}
    74         -} {1 3}
           74  +} {1 2}
    75     75   do_test where4-1.7 {
    76     76     count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL AND y=3}
    77     77   } {2 2}
    78     78   do_test where4-1.8 {
    79     79     count {SELECT rowid FROM t1 WHERE w=1 AND x IS NULL AND y>2}
    80     80   } {2 2}
    81     81   do_test where4-1.9 {
................................................................................
    94     94     count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL}
    95     95   } {7 2}
    96     96   do_test where4-1.14 {
    97     97     count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y IS NULL}
    98     98   } {7 2}
    99     99   do_test where4-1.15 {
   100    100     count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y<0}
   101         -} {2}
          101  +} {1}
   102    102   do_test where4-1.16 {
   103    103     count {SELECT rowid FROM t1 WHERE w IS NULL AND x IS NULL AND y>=0}
   104    104   } {1}
   105    105   
   106    106   do_test where4-2.1 {
   107    107     execsql {SELECT rowid FROM t1 ORDER BY w, x, y}
   108    108   } {7 2 1 4 3 6 5}

Changes to test/where8.test.

    83     83   do_test where8-1.8 {
    84     84     # 18 searches. 9 on the index cursor and 9 on the table cursor.
    85     85     execsql_status2 { SELECT c FROM t1 WHERE a > 1 AND c LIKE 'I%' }
    86     86   } {II III IV IX 0 0 18}
    87     87   
    88     88   do_test where8-1.9 {
    89     89     execsql_status2 { SELECT c FROM t1 WHERE a >= 9 OR b <= 'eight' }
    90         -} {IX X VIII 0 0 6}
           90  +} {IX X VIII 0 0 7}
    91     91   
    92     92   do_test where8-1.10 {
    93     93     execsql_status2 { 
    94     94       SELECT c FROM t1 WHERE (a >= 9 AND c != 'X') OR b <= 'eight' 
    95     95     }
    96         -} {IX VIII 0 0 6}
           96  +} {IX VIII 0 0 7}
    97     97   
    98     98   do_test where8-1.11 {
    99     99     execsql_status2 { 
   100    100       SELECT c FROM t1 WHERE (a >= 4 AND a <= 6) OR b = 'nine' 
   101    101     }
   102    102   } {IV V VI IX 0 0 10}
   103    103   

Changes to test/without_rowid1.test.

   194    194     INSERT INTO t4 VALUES('i');
   195    195     INSERT INTO t4 VALUES('ii');
   196    196     INSERT INTO t4 VALUES('iii');
   197    197   
   198    198     INSERT INTO t3 SELECT * FROM t4;
   199    199     SELECT * FROM t3;
   200    200   } {i ii iii}
          201  +
          202  +############################################################################
          203  +# Ticket [c34d0557f740c450709d6e33df72d4f3f651a3cc]
          204  +# Name resolution issue with WITHOUT ROWID
          205  +#
          206  +do_execsql_test 4.1 {
          207  +  CREATE TABLE t41(a PRIMARY KEY) WITHOUT ROWID;
          208  +  INSERT INTO t41 VALUES('abc');
          209  +  CREATE TABLE t42(x);
          210  +  INSERT INTO t42 VALUES('xyz');
          211  +  SELECT t42.rowid FROM t41, t42;
          212  +} {1}
          213  +do_execsql_test 4.2 {
          214  +  SELECT t42.rowid FROM t42, t41;
          215  +} {1}
   201    216     
   202    217   finish_test
   203         -

Changes to test/zerodamage.test.

   111    111     do_test zerodamage-3.1 {
   112    112       db close
   113    113       sqlite3 db file:test.db?psow=FALSE -uri 1
   114    114       db eval {
   115    115          UPDATE t1 SET y=randomblob(50) WHERE x=124;
   116    116       }
   117    117       file size test.db-wal
   118         -  } {8416}
          118  +  } {16800}
   119    119   }
   120    120   
   121    121   finish_test

Changes to tool/mksqlite3c.tcl.

   119    119      wal.h
   120    120      whereInt.h
   121    121   } {
   122    122     set available_hdr($hdr) 1
   123    123   }
   124    124   set available_hdr(sqliteInt.h) 0
   125    125   set available_hdr(sqlite3session.h) 0
   126         -set available_hdr(sqlite3.h) 0
   127    126   
   128    127   # 78 stars used for comment formatting.
   129    128   set s78 \
   130    129   {*****************************************************************************}
   131    130   
   132    131   # Insert a comment into the code
   133    132   #
................................................................................
   227    226   
   228    227   
   229    228   # Process the source files.  Process files containing commonly
   230    229   # used subroutines first in order to help the compiler find
   231    230   # inlining opportunities.
   232    231   #
   233    232   foreach file {
   234         -   sqlite3.h
   235    233      sqliteInt.h
   236    234   
   237    235      global.c
   238    236      ctime.c
   239    237      status.c
   240    238      date.c
   241    239      os.c

Added tool/vdbe_profile.tcl.

            1  +#!/bin/tclsh
            2  +#
            3  +# Run this script in the same directory as the "vdbe_profile.out" file.
            4  +# This script summarizes the results contained in that file.
            5  +#
            6  +if {![file readable vdbe_profile.out]} {
            7  +  error "run this script in the same directory as the vdbe_profile.out file"
            8  +}
            9  +set in [open vdbe_profile.out r]
           10  +set stmt {}
           11  +set allstmt {}
           12  +while {![eof $in]} {
           13  +  set line [gets $in]
           14  +  if {$line==""} continue
           15  +  if {[regexp {^---- } $line]} {
           16  +    set stmt [lindex $line 1]
           17  +    if {[info exists cnt($stmt)]} {
           18  +      incr cnt($stmt)
           19  +      set firsttime 0
           20  +    } else {
           21  +      set cnt($stmt) 1
           22  +      set sql($stmt) {}
           23  +      set firsttime 1
           24  +      lappend allstmt $stmt
           25  +    }
           26  +    continue;
           27  +  }
           28  +  if {[regexp {^-- } $line]} {
           29  +    if {$firsttime} {
           30  +      append sql($stmt) [string range $line 3 end]\n
           31  +    }
           32  +    continue
           33  +  }
           34  +  if {![regexp {^ *\d+ *\d+ *\d+ *\d+ ([A-Z].*)} $line all detail]} continue
           35  +  set c [lindex $line 0]
           36  +  set t [lindex $line 1]
           37  +  set addr [lindex $line 3]
           38  +  set op [lindex $line 4]
           39  +  if {[info exists opcnt($op)]} {
           40  +    incr opcnt($op) $c
           41  +    incr opcycle($op) $t
           42  +  } else {
           43  +    set opcnt($op) $c
           44  +    set opcycle($op) $t
           45  +  }
           46  +  if {[info exists stat($stmt,$addr)]} {
           47  +    foreach {cx tx detail} $stat($stmt,$addr) break
           48  +    incr cx $c
           49  +    incr tx $t
           50  +    set stat($stmt,$addr) [list $cx $tx $detail]
           51  +  } else {
           52  +    set stat($stmt,$addr) [list $c $t $detail]
           53  +  }
           54  +}
           55  +close $in
           56  +
           57  +foreach stmt $allstmt {
           58  +  puts "********************************************************************"
           59  +  puts [string trim $sql($stmt)]
           60  +  puts "Execution count: $cnt($stmt)"
           61  +  for {set i 0} {[info exists stat($stmt,$i)]} {incr i} {
           62  +    foreach {cx tx detail} $stat($stmt,$i) break
           63  +    if {$cx==0} {
           64  +      set ax 0
           65  +    } else {
           66  +      set ax [expr {$tx/$cx}]
           67  +    }
           68  +    puts [format {%8d %12d %12d %4d %s} $cx $tx $ax $i $detail]
           69  +  }
           70  +}
           71  +puts "********************************************************************"
           72  +puts "OPCODES:"
           73  +foreach op [lsort [array names opcnt]] {
           74  +  set cx $opcnt($op)
           75  +  set tx $opcycle($op)
           76  +  if {$cx==0} {
           77  +    set ax 0
           78  +  } else {
           79  +    set ax [expr {$tx/$cx}]
           80  +  }
           81  +  puts [format {%8d %12d %12d %s} $cx $tx $ax $op]
           82  +}