github.com/jdgcs/sqlite3@v1.12.1-0.20210908114423-bc5f96e4dd51/testdata/tcl/threadtest3.c (about)

     1  /*
     2  ** 2010-07-22
     3  **
     4  ** The author disclaims copyright to this source code.  In place of
     5  ** a legal notice, here is a blessing:
     6  **
     7  **    May you do good and not evil.
     8  **    May you find forgiveness for yourself and forgive others.
     9  **    May you share freely, never taking more than you give.
    10  **
    11  *************************************************************************
    12  **
    13  ** The code in this file runs a few multi-threaded test cases using the
    14  ** SQLite library. It can be compiled to an executable on unix using the
    15  ** following command:
    16  **
    17  **   gcc -O2 threadtest3.c sqlite3.c -ldl -lpthread -lm
    18  **
    19  ** Even though threadtest3.c is the only C source code file mentioned on
    20  ** the compiler command-line, #include macros are used to pull in additional
    21  ** C code files named "tt3_*.c".
    22  **
    23  ** After compiling, run this program with an optional argument telling
    24  ** which test to run.  All tests are run if no argument is given.  The
    25  ** argument can be a glob pattern to match multiple tests.  Examples:
    26  **
    27  **        ./a.out                 -- Run all tests
    28  **        ./a.out walthread3      -- Run the "walthread3" test
    29  **        ./a.out 'wal*'          -- Run all of the wal* tests
    30  **        ./a.out --help          -- List all available tests
    31  **
    32  ** The exit status is non-zero if any test fails.
    33  */
    34  
    35  /* 
    36  ** The "Set Error Line" macro.
    37  */
    38  #define SEL(e) ((e)->iLine = ((e)->rc ? (e)->iLine : __LINE__))
    39  
    40  /* Database functions */
    41  #define opendb(w,x,y,z)         (SEL(w), opendb_x(w,x,y,z))
    42  #define closedb(y,z)            (SEL(y), closedb_x(y,z))
    43  
    44  /* Functions to execute SQL */
    45  #define sql_script(x,y,z)       (SEL(x), sql_script_x(x,y,z))
    46  #define integrity_check(x,y)    (SEL(x), integrity_check_x(x,y))
    47  #define execsql_i64(x,y,...)    (SEL(x), execsql_i64_x(x,y,__VA_ARGS__))
    48  #define execsql_text(x,y,z,...) (SEL(x), execsql_text_x(x,y,z,__VA_ARGS__))
    49  #define execsql(x,y,...)        (SEL(x), (void)execsql_i64_x(x,y,__VA_ARGS__))
    50  #define sql_script_printf(x,y,z,...) (                \
    51      SEL(x), sql_script_printf_x(x,y,z,__VA_ARGS__)    \
    52  ) 
    53  
    54  /* Thread functions */
    55  #define launch_thread(w,x,y,z)     (SEL(w), launch_thread_x(w,x,y,z))
    56  #define join_all_threads(y,z)      (SEL(y), join_all_threads_x(y,z))
    57  
    58  /* Timer functions */
    59  #define setstoptime(y,z)        (SEL(y), setstoptime_x(y,z))
    60  #define timetostop(z)           (SEL(z), timetostop_x(z))
    61  
    62  /* Report/clear errors. */
    63  #define test_error(z, ...)      test_error_x(z, sqlite3_mprintf(__VA_ARGS__))
    64  #define clear_error(y,z)        clear_error_x(y, z)
    65  
    66  /* File-system operations */
    67  #define filesize(y,z)           (SEL(y), filesize_x(y,z))
    68  #define filecopy(x,y,z)         (SEL(x), filecopy_x(x,y,z))
    69  
    70  #define PTR2INT(x) ((int)((intptr_t)x))
    71  #define INT2PTR(x) ((void*)((intptr_t)x))
    72  
    73  /*
    74  ** End of test code/infrastructure interface macros.
    75  *************************************************************************/
    76  
    77  
    78  
    79  
    80  #include <sqlite3.h>
    81  #include <unistd.h>
    82  #include <stdio.h>
    83  #include <pthread.h>
    84  #include <assert.h>
    85  #include <sys/types.h> 
    86  #include <sys/stat.h> 
    87  #include <string.h>
    88  #include <fcntl.h>
    89  #include <errno.h>
    90  
    91  #include "test_multiplex.h"
    92  
    93  /* Required to link test_multiplex.c */
    94  #ifndef SQLITE_OMIT_WSD
    95  int sqlite3PendingByte = 0x40000000;
    96  #endif
    97  
    98  /*
    99   * This code implements the MD5 message-digest algorithm.
   100   * The algorithm is due to Ron Rivest.  This code was
   101   * written by Colin Plumb in 1993, no copyright is claimed.
   102   * This code is in the public domain; do with it what you wish.
   103   *
   104   * Equivalent code is available from RSA Data Security, Inc.
   105   * This code has been tested against that, and is equivalent,
   106   * except that you don't need to include two pages of legalese
   107   * with every copy.
   108   *
   109   * To compute the message digest of a chunk of bytes, declare an
   110   * MD5Context structure, pass it to MD5Init, call MD5Update as
   111   * needed on buffers full of bytes, and then call MD5Final, which
   112   * will fill a supplied 16-byte array with the digest.
   113   */
   114  
   115  /*
   116   * If compiled on a machine that doesn't have a 32-bit integer,
   117   * you just set "uint32" to the appropriate datatype for an
   118   * unsigned 32-bit integer.  For example:
   119   *
   120   *       cc -Duint32='unsigned long' md5.c
   121   *
   122   */
   123  #ifndef uint32
   124  #  define uint32 unsigned int
   125  #endif
   126  
   127  struct MD5Context {
   128    int isInit;
   129    uint32 buf[4];
   130    uint32 bits[2];
   131    union {
   132      unsigned char in[64];
   133      uint32 in32[16];
   134    } u;
   135  };
   136  typedef struct MD5Context MD5Context;
   137  
   138  /*
   139   * Note: this code is harmless on little-endian machines.
   140   */
   141  static void byteReverse (unsigned char *buf, unsigned longs){
   142    uint32 t;
   143    do {
   144      t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |
   145            ((unsigned)buf[1]<<8 | buf[0]);
   146      *(uint32 *)buf = t;
   147      buf += 4;
   148    } while (--longs);
   149  }
   150  /* The four core functions - F1 is optimized somewhat */
   151  
   152  /* #define F1(x, y, z) (x & y | ~x & z) */
   153  #define F1(x, y, z) (z ^ (x & (y ^ z)))
   154  #define F2(x, y, z) F1(z, x, y)
   155  #define F3(x, y, z) (x ^ y ^ z)
   156  #define F4(x, y, z) (y ^ (x | ~z))
   157  
   158  /* This is the central step in the MD5 algorithm. */
   159  #define MD5STEP(f, w, x, y, z, data, s) \
   160    ( w += f(x, y, z) + data,  w = w<<s | w>>(32-s),  w += x )
   161  
   162  /*
   163   * The core of the MD5 algorithm, this alters an existing MD5 hash to
   164   * reflect the addition of 16 longwords of new data.  MD5Update blocks
   165   * the data and converts bytes into longwords for this routine.
   166   */
   167  static void MD5Transform(uint32 buf[4], const uint32 in[16]){
   168    register uint32 a, b, c, d;
   169  
   170    a = buf[0];
   171    b = buf[1];
   172    c = buf[2];
   173    d = buf[3];
   174  
   175    MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478,  7);
   176    MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);
   177    MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);
   178    MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);
   179    MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf,  7);
   180    MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);
   181    MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);
   182    MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);
   183    MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8,  7);
   184    MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);
   185    MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);
   186    MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);
   187    MD5STEP(F1, a, b, c, d, in[12]+0x6b901122,  7);
   188    MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);
   189    MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);
   190    MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);
   191  
   192    MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562,  5);
   193    MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340,  9);
   194    MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);
   195    MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);
   196    MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d,  5);
   197    MD5STEP(F2, d, a, b, c, in[10]+0x02441453,  9);
   198    MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);
   199    MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);
   200    MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6,  5);
   201    MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6,  9);
   202    MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);
   203    MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);
   204    MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905,  5);
   205    MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8,  9);
   206    MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);
   207    MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);
   208  
   209    MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942,  4);
   210    MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);
   211    MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);
   212    MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);
   213    MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44,  4);
   214    MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);
   215    MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);
   216    MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);
   217    MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6,  4);
   218    MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);
   219    MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);
   220    MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);
   221    MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039,  4);
   222    MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);
   223    MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);
   224    MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);
   225  
   226    MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244,  6);
   227    MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);
   228    MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);
   229    MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);
   230    MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3,  6);
   231    MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);
   232    MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);
   233    MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);
   234    MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f,  6);
   235    MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);
   236    MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);
   237    MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);
   238    MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82,  6);
   239    MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);
   240    MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);
   241    MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);
   242  
   243    buf[0] += a;
   244    buf[1] += b;
   245    buf[2] += c;
   246    buf[3] += d;
   247  }
   248  
   249  /*
   250   * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
   251   * initialization constants.
   252   */
   253  static void MD5Init(MD5Context *ctx){
   254    ctx->isInit = 1;
   255    ctx->buf[0] = 0x67452301;
   256    ctx->buf[1] = 0xefcdab89;
   257    ctx->buf[2] = 0x98badcfe;
   258    ctx->buf[3] = 0x10325476;
   259    ctx->bits[0] = 0;
   260    ctx->bits[1] = 0;
   261  }
   262  
   263  /*
   264   * Update context to reflect the concatenation of another buffer full
   265   * of bytes.
   266   */
   267  static 
   268  void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){
   269    uint32 t;
   270  
   271    /* Update bitcount */
   272  
   273    t = ctx->bits[0];
   274    if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)
   275      ctx->bits[1]++; /* Carry from low to high */
   276    ctx->bits[1] += len >> 29;
   277  
   278    t = (t >> 3) & 0x3f;    /* Bytes already in shsInfo->data */
   279  
   280    /* Handle any leading odd-sized chunks */
   281  
   282    if ( t ) {
   283      unsigned char *p = (unsigned char *)ctx->u.in + t;
   284  
   285      t = 64-t;
   286      if (len < t) {
   287        memcpy(p, buf, len);
   288        return;
   289      }
   290      memcpy(p, buf, t);
   291      byteReverse(ctx->u.in, 16);
   292      MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
   293      buf += t;
   294      len -= t;
   295    }
   296  
   297    /* Process data in 64-byte chunks */
   298  
   299    while (len >= 64) {
   300      memcpy(ctx->u.in, buf, 64);
   301      byteReverse(ctx->u.in, 16);
   302      MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
   303      buf += 64;
   304      len -= 64;
   305    }
   306  
   307    /* Handle any remaining bytes of data. */
   308  
   309    memcpy(ctx->u.in, buf, len);
   310  }
   311  
   312  /*
   313   * Final wrapup - pad to 64-byte boundary with the bit pattern 
   314   * 1 0* (64-bit count of bits processed, MSB-first)
   315   */
   316  static void MD5Final(unsigned char digest[16], MD5Context *ctx){
   317    unsigned count;
   318    unsigned char *p;
   319  
   320    /* Compute number of bytes mod 64 */
   321    count = (ctx->bits[0] >> 3) & 0x3F;
   322  
   323    /* Set the first char of padding to 0x80.  This is safe since there is
   324       always at least one byte free */
   325    p = ctx->u.in + count;
   326    *p++ = 0x80;
   327  
   328    /* Bytes of padding needed to make 64 bytes */
   329    count = 64 - 1 - count;
   330  
   331    /* Pad out to 56 mod 64 */
   332    if (count < 8) {
   333      /* Two lots of padding:  Pad the first block to 64 bytes */
   334      memset(p, 0, count);
   335      byteReverse(ctx->u.in, 16);
   336      MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
   337  
   338      /* Now fill the next block with 56 bytes */
   339      memset(ctx->u.in, 0, 56);
   340    } else {
   341      /* Pad block to 56 bytes */
   342      memset(p, 0, count-8);
   343    }
   344    byteReverse(ctx->u.in, 14);
   345  
   346    /* Append length in bits and transform */
   347    ctx->u.in32[14] = ctx->bits[0];
   348    ctx->u.in32[15] = ctx->bits[1];
   349  
   350    MD5Transform(ctx->buf, (uint32 *)ctx->u.in);
   351    byteReverse((unsigned char *)ctx->buf, 4);
   352    memcpy(digest, ctx->buf, 16);
   353    memset(ctx, 0, sizeof(*ctx));    /* In case it is sensitive */
   354  }
   355  
   356  /*
   357  ** Convert a 128-bit MD5 digest into a 32-digit base-16 number.
   358  */
   359  static void MD5DigestToBase16(unsigned char *digest, char *zBuf){
   360    static char const zEncode[] = "0123456789abcdef";
   361    int i, j;
   362  
   363    for(j=i=0; i<16; i++){
   364      int a = digest[i];
   365      zBuf[j++] = zEncode[(a>>4)&0xf];
   366      zBuf[j++] = zEncode[a & 0xf];
   367    }
   368    zBuf[j] = 0;
   369  }
   370  
   371  /*
   372  ** During testing, the special md5sum() aggregate function is available.
   373  ** inside SQLite.  The following routines implement that function.
   374  */
   375  static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){
   376    MD5Context *p;
   377    int i;
   378    if( argc<1 ) return;
   379    p = sqlite3_aggregate_context(context, sizeof(*p));
   380    if( p==0 ) return;
   381    if( !p->isInit ){
   382      MD5Init(p);
   383    }
   384    for(i=0; i<argc; i++){
   385      const char *zData = (char*)sqlite3_value_text(argv[i]);
   386      if( zData ){
   387        MD5Update(p, (unsigned char*)zData, strlen(zData));
   388      }
   389    }
   390  }
   391  static void md5finalize(sqlite3_context *context){
   392    MD5Context *p;
   393    unsigned char digest[16];
   394    char zBuf[33];
   395    p = sqlite3_aggregate_context(context, sizeof(*p));
   396    MD5Final(digest,p);
   397    MD5DigestToBase16(digest, zBuf);
   398    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
   399  }
   400  
   401  /*
   402  ** End of copied md5sum() code.
   403  **************************************************************************/
   404  
   405  typedef sqlite3_int64 i64;
   406  
   407  typedef struct Error Error;
   408  typedef struct Sqlite Sqlite;
   409  typedef struct Statement Statement;
   410  
   411  typedef struct Threadset Threadset;
   412  typedef struct Thread Thread;
   413  
   414  /* Total number of errors in this process so far. */
   415  static int nGlobalErr = 0;
   416  
   417  struct Error {
   418    int rc;
   419    int iLine;
   420    char *zErr;
   421  };
   422  
   423  struct Sqlite {
   424    sqlite3 *db;                    /* Database handle */
   425    Statement *pCache;              /* Linked list of cached statements */
   426    int nText;                      /* Size of array at aText[] */
   427    char **aText;                   /* Stored text results */
   428  };
   429  
   430  struct Statement {
   431    sqlite3_stmt *pStmt;            /* Pre-compiled statement handle */
   432    Statement *pNext;               /* Next statement in linked-list */
   433  };
   434  
   435  struct Thread {
   436    int iTid;                       /* Thread number within test */
   437    void* pArg;                     /* Pointer argument passed by caller */
   438  
   439    pthread_t tid;                  /* Thread id */
   440    char *(*xProc)(int, void*);     /* Thread main proc */
   441    Thread *pNext;                  /* Next in this list of threads */
   442  };
   443  
   444  struct Threadset {
   445    int iMaxTid;                    /* Largest iTid value allocated so far */
   446    Thread *pThread;                /* Linked list of threads */
   447  };
   448  
   449  static void free_err(Error *p){
   450    sqlite3_free(p->zErr);
   451    p->zErr = 0;
   452    p->rc = 0;
   453  }
   454  
   455  static void print_err(Error *p){
   456    if( p->rc!=SQLITE_OK ){
   457      int isWarn = 0;
   458      if( p->rc==SQLITE_SCHEMA ) isWarn = 1;
   459      if( sqlite3_strglob("* - no such table: *",p->zErr)==0 ) isWarn = 1;
   460      printf("%s: (%d) \"%s\" at line %d\n", isWarn ? "Warning" : "Error",
   461              p->rc, p->zErr, p->iLine);
   462      if( !isWarn ) nGlobalErr++;
   463      fflush(stdout);
   464    }
   465  }
   466  
   467  static void print_and_free_err(Error *p){
   468    print_err(p);
   469    free_err(p);
   470  }
   471  
   472  static void system_error(Error *pErr, int iSys){
   473    pErr->rc = iSys;
   474    pErr->zErr = (char *)sqlite3_malloc(512);
   475    strerror_r(iSys, pErr->zErr, 512);
   476    pErr->zErr[511] = '\0';
   477  }
   478  
   479  static void sqlite_error(
   480    Error *pErr, 
   481    Sqlite *pDb, 
   482    const char *zFunc
   483  ){
   484    pErr->rc = sqlite3_errcode(pDb->db);
   485    pErr->zErr = sqlite3_mprintf(
   486        "sqlite3_%s() - %s (%d)", zFunc, sqlite3_errmsg(pDb->db),
   487        sqlite3_extended_errcode(pDb->db)
   488    );
   489  }
   490  
   491  static void test_error_x(
   492    Error *pErr,
   493    char *zErr
   494  ){
   495    if( pErr->rc==SQLITE_OK ){
   496      pErr->rc = 1;
   497      pErr->zErr = zErr;
   498    }else{
   499      sqlite3_free(zErr);
   500    }
   501  }
   502  
   503  static void clear_error_x(
   504    Error *pErr,
   505    int rc
   506  ){
   507    if( pErr->rc==rc ){
   508      pErr->rc = SQLITE_OK;
   509      sqlite3_free(pErr->zErr);
   510      pErr->zErr = 0;
   511    }
   512  }
   513  
   514  static int busyhandler(void *pArg, int n){
   515    usleep(10*1000);
   516    return 1;
   517  }
   518  
   519  static void opendb_x(
   520    Error *pErr,                    /* IN/OUT: Error code */
   521    Sqlite *pDb,                    /* OUT: Database handle */
   522    const char *zFile,              /* Database file name */
   523    int bDelete                     /* True to delete db file before opening */
   524  ){
   525    if( pErr->rc==SQLITE_OK ){
   526      int rc;
   527      int flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI;
   528      if( bDelete ) unlink(zFile);
   529      rc = sqlite3_open_v2(zFile, &pDb->db, flags, 0);
   530      if( rc ){
   531        sqlite_error(pErr, pDb, "open");
   532        sqlite3_close(pDb->db);
   533        pDb->db = 0;
   534      }else{
   535        sqlite3_create_function(
   536            pDb->db, "md5sum", -1, SQLITE_UTF8, 0, 0, md5step, md5finalize
   537        );
   538        sqlite3_busy_handler(pDb->db, busyhandler, 0);
   539        sqlite3_exec(pDb->db, "PRAGMA synchronous=OFF", 0, 0, 0);
   540      }
   541    }
   542  }
   543  
   544  static void closedb_x(
   545    Error *pErr,                    /* IN/OUT: Error code */
   546    Sqlite *pDb                     /* OUT: Database handle */
   547  ){
   548    int rc;
   549    int i;
   550    Statement *pIter;
   551    Statement *pNext;
   552    for(pIter=pDb->pCache; pIter; pIter=pNext){
   553      pNext = pIter->pNext;
   554      sqlite3_finalize(pIter->pStmt);
   555      sqlite3_free(pIter);
   556    }
   557    for(i=0; i<pDb->nText; i++){
   558      sqlite3_free(pDb->aText[i]);
   559    }
   560    sqlite3_free(pDb->aText);
   561    rc = sqlite3_close(pDb->db);
   562    if( rc && pErr->rc==SQLITE_OK ){
   563      pErr->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(pDb->db));
   564    }
   565    memset(pDb, 0, sizeof(Sqlite));
   566  }
   567  
   568  static void sql_script_x(
   569    Error *pErr,                    /* IN/OUT: Error code */
   570    Sqlite *pDb,                    /* Database handle */
   571    const char *zSql                /* SQL script to execute */
   572  ){
   573    if( pErr->rc==SQLITE_OK ){
   574      pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);
   575    }
   576  }
   577  
   578  static void sql_script_printf_x(
   579    Error *pErr,                    /* IN/OUT: Error code */
   580    Sqlite *pDb,                    /* Database handle */
   581    const char *zFormat,            /* SQL printf format string */
   582    ...                             /* Printf args */
   583  ){
   584    va_list ap;                     /* ... printf arguments */
   585    va_start(ap, zFormat);
   586    if( pErr->rc==SQLITE_OK ){
   587      char *zSql = sqlite3_vmprintf(zFormat, ap);
   588      pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);
   589      sqlite3_free(zSql);
   590    }
   591    va_end(ap);
   592  }
   593  
   594  static Statement *getSqlStatement(
   595    Error *pErr,                    /* IN/OUT: Error code */
   596    Sqlite *pDb,                    /* Database handle */
   597    const char *zSql                /* SQL statement */
   598  ){
   599    Statement *pRet;
   600    int rc;
   601  
   602    for(pRet=pDb->pCache; pRet; pRet=pRet->pNext){
   603      if( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) ){
   604        return pRet;
   605      }
   606    }
   607  
   608    pRet = sqlite3_malloc(sizeof(Statement));
   609    rc = sqlite3_prepare_v2(pDb->db, zSql, -1, &pRet->pStmt, 0);
   610    if( rc!=SQLITE_OK ){
   611      sqlite_error(pErr, pDb, "prepare_v2");
   612      return 0;
   613    }
   614    assert( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) );
   615  
   616    pRet->pNext = pDb->pCache;
   617    pDb->pCache = pRet;
   618    return pRet;
   619  }
   620  
   621  static sqlite3_stmt *getAndBindSqlStatement(
   622    Error *pErr,                    /* IN/OUT: Error code */
   623    Sqlite *pDb,                    /* Database handle */
   624    va_list ap                      /* SQL followed by parameters */
   625  ){
   626    Statement *pStatement;          /* The SQLite statement wrapper */
   627    sqlite3_stmt *pStmt;            /* The SQLite statement to return */
   628    int i;                          /* Used to iterate through parameters */
   629  
   630    pStatement = getSqlStatement(pErr, pDb, va_arg(ap, const char *));
   631    if( !pStatement ) return 0;
   632    pStmt = pStatement->pStmt;
   633    for(i=1; i<=sqlite3_bind_parameter_count(pStmt); i++){
   634      const char *zName = sqlite3_bind_parameter_name(pStmt, i);
   635      void * pArg = va_arg(ap, void*);
   636  
   637      switch( zName[1] ){
   638        case 'i':
   639          sqlite3_bind_int64(pStmt, i, *(i64 *)pArg);
   640          break;
   641  
   642        default:
   643          pErr->rc = 1;
   644          pErr->zErr = sqlite3_mprintf("Cannot discern type: \"%s\"", zName);
   645          pStmt = 0;
   646          break;
   647      }
   648    }
   649  
   650    return pStmt;
   651  }
   652  
   653  static i64 execsql_i64_x(
   654    Error *pErr,                    /* IN/OUT: Error code */
   655    Sqlite *pDb,                    /* Database handle */
   656    ...                             /* SQL and pointers to parameter values */
   657  ){
   658    i64 iRet = 0;
   659    if( pErr->rc==SQLITE_OK ){
   660      sqlite3_stmt *pStmt;          /* SQL statement to execute */
   661      va_list ap;                   /* ... arguments */
   662      va_start(ap, pDb);
   663      pStmt = getAndBindSqlStatement(pErr, pDb, ap);
   664      if( pStmt ){
   665        int first = 1;
   666        while( SQLITE_ROW==sqlite3_step(pStmt) ){
   667          if( first && sqlite3_column_count(pStmt)>0 ){
   668            iRet = sqlite3_column_int64(pStmt, 0);
   669          }
   670          first = 0;
   671        }
   672        if( SQLITE_OK!=sqlite3_reset(pStmt) ){
   673          sqlite_error(pErr, pDb, "reset");
   674        }
   675      }
   676      va_end(ap);
   677    }
   678    return iRet;
   679  }
   680  
   681  static char * execsql_text_x(
   682    Error *pErr,                    /* IN/OUT: Error code */
   683    Sqlite *pDb,                    /* Database handle */
   684    int iSlot,                      /* Db handle slot to store text in */
   685    ...                             /* SQL and pointers to parameter values */
   686  ){
   687    char *zRet = 0;
   688  
   689    if( iSlot>=pDb->nText ){
   690      int nByte = sizeof(char *)*(iSlot+1);
   691      pDb->aText = (char **)sqlite3_realloc(pDb->aText, nByte);
   692      memset(&pDb->aText[pDb->nText], 0, sizeof(char*)*(iSlot+1-pDb->nText));
   693      pDb->nText = iSlot+1;
   694    }
   695  
   696    if( pErr->rc==SQLITE_OK ){
   697      sqlite3_stmt *pStmt;          /* SQL statement to execute */
   698      va_list ap;                   /* ... arguments */
   699      va_start(ap, iSlot);
   700      pStmt = getAndBindSqlStatement(pErr, pDb, ap);
   701      if( pStmt ){
   702        int first = 1;
   703        while( SQLITE_ROW==sqlite3_step(pStmt) ){
   704          if( first && sqlite3_column_count(pStmt)>0 ){
   705            zRet = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));
   706            sqlite3_free(pDb->aText[iSlot]);
   707            pDb->aText[iSlot] = zRet;
   708          }
   709          first = 0;
   710        }
   711        if( SQLITE_OK!=sqlite3_reset(pStmt) ){
   712          sqlite_error(pErr, pDb, "reset");
   713        }
   714      }
   715      va_end(ap);
   716    }
   717  
   718    return zRet;
   719  }
   720  
   721  static void integrity_check_x(
   722    Error *pErr,                    /* IN/OUT: Error code */
   723    Sqlite *pDb                     /* Database handle */
   724  ){
   725    if( pErr->rc==SQLITE_OK ){
   726      Statement *pStatement;        /* Statement to execute */
   727      char *zErr = 0;               /* Integrity check error */
   728  
   729      pStatement = getSqlStatement(pErr, pDb, "PRAGMA integrity_check");
   730      if( pStatement ){
   731        sqlite3_stmt *pStmt = pStatement->pStmt;
   732        while( SQLITE_ROW==sqlite3_step(pStmt) ){
   733          const char *z = (const char*)sqlite3_column_text(pStmt, 0);
   734          if( strcmp(z, "ok") ){
   735            if( zErr==0 ){
   736              zErr = sqlite3_mprintf("%s", z);
   737            }else{
   738              zErr = sqlite3_mprintf("%z\n%s", zErr, z);
   739            }
   740          }
   741        }
   742        sqlite3_reset(pStmt);
   743  
   744        if( zErr ){
   745          pErr->zErr = zErr;
   746          pErr->rc = 1;
   747        }
   748      }
   749    }
   750  }
   751  
   752  static void *launch_thread_main(void *pArg){
   753    Thread *p = (Thread *)pArg;
   754    return (void *)p->xProc(p->iTid, p->pArg);
   755  }
   756  
   757  static void launch_thread_x(
   758    Error *pErr,                    /* IN/OUT: Error code */
   759    Threadset *pThreads,            /* Thread set */
   760    char *(*xProc)(int, void*),     /* Proc to run */
   761    void *pArg                      /* Argument passed to thread proc */
   762  ){
   763    if( pErr->rc==SQLITE_OK ){
   764      int iTid = ++pThreads->iMaxTid;
   765      Thread *p;
   766      int rc;
   767  
   768      p = (Thread *)sqlite3_malloc(sizeof(Thread));
   769      memset(p, 0, sizeof(Thread));
   770      p->iTid = iTid;
   771      p->pArg = pArg;
   772      p->xProc = xProc;
   773  
   774      rc = pthread_create(&p->tid, NULL, launch_thread_main, (void *)p);
   775      if( rc!=0 ){
   776        system_error(pErr, rc);
   777        sqlite3_free(p);
   778      }else{
   779        p->pNext = pThreads->pThread;
   780        pThreads->pThread = p;
   781      }
   782    }
   783  }
   784  
   785  static void join_all_threads_x(
   786    Error *pErr,                    /* IN/OUT: Error code */
   787    Threadset *pThreads             /* Thread set */
   788  ){
   789    Thread *p;
   790    Thread *pNext;
   791    for(p=pThreads->pThread; p; p=pNext){
   792      void *ret;
   793      pNext = p->pNext;
   794      int rc;
   795      rc = pthread_join(p->tid, &ret);
   796      if( rc!=0 ){
   797        if( pErr->rc==SQLITE_OK ) system_error(pErr, rc);
   798      }else{
   799        printf("Thread %d says: %s\n", p->iTid, (ret==0 ? "..." : (char *)ret));
   800        fflush(stdout);
   801      }
   802      sqlite3_free(p);
   803    }
   804    pThreads->pThread = 0;
   805  }
   806  
   807  static i64 filesize_x(
   808    Error *pErr,
   809    const char *zFile
   810  ){
   811    i64 iRet = 0;
   812    if( pErr->rc==SQLITE_OK ){
   813      struct stat sStat;
   814      if( stat(zFile, &sStat) ){
   815        iRet = -1;
   816      }else{
   817        iRet = sStat.st_size;
   818      }
   819    }
   820    return iRet;
   821  }
   822  
   823  static void filecopy_x(
   824    Error *pErr,
   825    const char *zFrom,
   826    const char *zTo
   827  ){
   828    if( pErr->rc==SQLITE_OK ){
   829      i64 nByte = filesize_x(pErr, zFrom);
   830      if( nByte<0 ){
   831        test_error_x(pErr, sqlite3_mprintf("no such file: %s", zFrom));
   832      }else{
   833        i64 iOff;
   834        char aBuf[1024];
   835        int fd1;
   836        int fd2;
   837        unlink(zTo);
   838  
   839        fd1 = open(zFrom, O_RDONLY);
   840        if( fd1<0 ){
   841          system_error(pErr, errno);
   842          return;
   843        }
   844        fd2 = open(zTo, O_RDWR|O_CREAT|O_EXCL, 0644);
   845        if( fd2<0 ){
   846          system_error(pErr, errno);
   847          close(fd1);
   848          return;
   849        }
   850  
   851        iOff = 0;
   852        while( iOff<nByte ){
   853          int nCopy = sizeof(aBuf);
   854          if( nCopy+iOff>nByte ){
   855            nCopy = nByte - iOff;
   856          }
   857          if( nCopy!=read(fd1, aBuf, nCopy) ){
   858            system_error(pErr, errno);
   859            break;
   860          }
   861          if( nCopy!=write(fd2, aBuf, nCopy) ){
   862            system_error(pErr, errno);
   863            break;
   864          }
   865          iOff += nCopy;
   866        }
   867  
   868        close(fd1);
   869        close(fd2);
   870      }
   871    }
   872  }
   873  
   874  /* 
   875  ** Used by setstoptime() and timetostop().
   876  */
   877  static double timelimit = 0.0;
   878  
   879  static double currentTime(void){
   880    double t;
   881    static sqlite3_vfs *pTimelimitVfs = 0;
   882    if( pTimelimitVfs==0 ) pTimelimitVfs = sqlite3_vfs_find(0);
   883    if( pTimelimitVfs->iVersion>=2 && pTimelimitVfs->xCurrentTimeInt64!=0 ){
   884      sqlite3_int64 tm;
   885      pTimelimitVfs->xCurrentTimeInt64(pTimelimitVfs, &tm);
   886      t = tm/86400000.0;
   887    }else{
   888      pTimelimitVfs->xCurrentTime(pTimelimitVfs, &t);
   889    }
   890    return t;
   891  }
   892  
   893  static void setstoptime_x(
   894    Error *pErr,                    /* IN/OUT: Error code */
   895    int nMs                         /* Milliseconds until "stop time" */
   896  ){
   897    if( pErr->rc==SQLITE_OK ){
   898      double t = currentTime();
   899      timelimit = t + ((double)nMs)/(1000.0*60.0*60.0*24.0);
   900    }
   901  }
   902  
   903  static int timetostop_x(
   904    Error *pErr                     /* IN/OUT: Error code */
   905  ){
   906    int ret = 1;
   907    if( pErr->rc==SQLITE_OK ){
   908      double t = currentTime();
   909      ret = (t >= timelimit);
   910    }
   911    return ret;
   912  }
   913  
   914  
   915  /*************************************************************************
   916  **************************************************************************
   917  **************************************************************************
   918  ** End infrastructure. Begin tests.
   919  */
   920  
   921  #define WALTHREAD1_NTHREAD  10
   922  #define WALTHREAD3_NTHREAD  6
   923  
   924  static char *walthread1_thread(int iTid, void *pArg){
   925    Error err = {0};                /* Error code and message */
   926    Sqlite db = {0};                /* SQLite database connection */
   927    int nIter = 0;                  /* Iterations so far */
   928  
   929    opendb(&err, &db, "test.db", 0);
   930    while( !timetostop(&err) ){
   931      const char *azSql[] = {
   932        "SELECT md5sum(x) FROM t1 WHERE rowid != (SELECT max(rowid) FROM t1)",
   933        "SELECT x FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1)",
   934      };
   935      char *z1, *z2, *z3;
   936  
   937      execsql(&err, &db, "BEGIN");
   938      integrity_check(&err, &db);
   939      z1 = execsql_text(&err, &db, 1, azSql[0]);
   940      z2 = execsql_text(&err, &db, 2, azSql[1]);
   941      z3 = execsql_text(&err, &db, 3, azSql[0]);
   942      execsql(&err, &db, "COMMIT");
   943  
   944      if( strcmp(z1, z2) || strcmp(z1, z3) ){
   945        test_error(&err, "Failed read: %s %s %s", z1, z2, z3);
   946      }
   947  
   948      sql_script(&err, &db,
   949          "BEGIN;"
   950            "INSERT INTO t1 VALUES(randomblob(100));"
   951            "INSERT INTO t1 VALUES(randomblob(100));"
   952            "INSERT INTO t1 SELECT md5sum(x) FROM t1;"
   953          "COMMIT;"
   954      );
   955      nIter++;
   956    }
   957    closedb(&err, &db);
   958  
   959    print_and_free_err(&err);
   960    return sqlite3_mprintf("%d iterations", nIter);
   961  }
   962  
   963  static char *walthread1_ckpt_thread(int iTid, void *pArg){
   964    Error err = {0};                /* Error code and message */
   965    Sqlite db = {0};                /* SQLite database connection */
   966    int nCkpt = 0;                  /* Checkpoints so far */
   967  
   968    opendb(&err, &db, "test.db", 0);
   969    while( !timetostop(&err) ){
   970      usleep(500*1000);
   971      execsql(&err, &db, "PRAGMA wal_checkpoint");
   972      if( err.rc==SQLITE_OK ) nCkpt++;
   973      clear_error(&err, SQLITE_BUSY);
   974    }
   975    closedb(&err, &db);
   976  
   977    print_and_free_err(&err);
   978    return sqlite3_mprintf("%d checkpoints", nCkpt);
   979  }
   980  
   981  static void walthread1(int nMs){
   982    Error err = {0};                /* Error code and message */
   983    Sqlite db = {0};                /* SQLite database connection */
   984    Threadset threads = {0};        /* Test threads */
   985    int i;                          /* Iterator variable */
   986  
   987    opendb(&err, &db, "test.db", 1);
   988    sql_script(&err, &db,
   989        "PRAGMA journal_mode = WAL;"
   990        "CREATE TABLE t1(x PRIMARY KEY);"
   991        "INSERT INTO t1 VALUES(randomblob(100));"
   992        "INSERT INTO t1 VALUES(randomblob(100));"
   993        "INSERT INTO t1 SELECT md5sum(x) FROM t1;"
   994    );
   995    closedb(&err, &db);
   996  
   997    setstoptime(&err, nMs);
   998    for(i=0; i<WALTHREAD1_NTHREAD; i++){
   999      launch_thread(&err, &threads, walthread1_thread, 0);
  1000    }
  1001    launch_thread(&err, &threads, walthread1_ckpt_thread, 0);
  1002    join_all_threads(&err, &threads);
  1003  
  1004    print_and_free_err(&err);
  1005  }
  1006  
  1007  static char *walthread2_thread(int iTid, void *pArg){
  1008    Error err = {0};                /* Error code and message */
  1009    Sqlite db = {0};                /* SQLite database connection */
  1010    int anTrans[2] = {0, 0};        /* Number of WAL and Rollback transactions */
  1011    int iArg = PTR2INT(pArg);
  1012  
  1013    const char *zJournal = "PRAGMA journal_mode = WAL";
  1014    if( iArg ){ zJournal = "PRAGMA journal_mode = DELETE"; }
  1015  
  1016    while( !timetostop(&err) ){
  1017      int journal_exists = 0;
  1018      int wal_exists = 0;
  1019  
  1020      opendb(&err, &db, "test.db", 0);
  1021  
  1022      sql_script(&err, &db, zJournal);
  1023      clear_error(&err, SQLITE_BUSY);
  1024      sql_script(&err, &db, "BEGIN");
  1025      sql_script(&err, &db, "INSERT INTO t1 VALUES(NULL, randomblob(100))");
  1026  
  1027      journal_exists = (filesize(&err, "test.db-journal") >= 0);
  1028      wal_exists = (filesize(&err, "test.db-wal") >= 0);
  1029      if( (journal_exists+wal_exists)!=1 ){
  1030        test_error(&err, "File system looks incorrect (%d, %d)", 
  1031            journal_exists, wal_exists
  1032        );
  1033      }
  1034      anTrans[journal_exists]++;
  1035  
  1036      sql_script(&err, &db, "COMMIT");
  1037      integrity_check(&err, &db);
  1038      closedb(&err, &db);
  1039    }
  1040  
  1041    print_and_free_err(&err);
  1042    return sqlite3_mprintf("W %d R %d", anTrans[0], anTrans[1]);
  1043  }
  1044  
  1045  static void walthread2(int nMs){
  1046    Error err = {0};
  1047    Sqlite db = {0};
  1048    Threadset threads = {0};
  1049  
  1050    opendb(&err, &db, "test.db", 1);
  1051    sql_script(&err, &db, "CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE)");
  1052    closedb(&err, &db);
  1053  
  1054    setstoptime(&err, nMs);
  1055    launch_thread(&err, &threads, walthread2_thread, 0);
  1056    launch_thread(&err, &threads, walthread2_thread, 0);
  1057    launch_thread(&err, &threads, walthread2_thread, (void*)1);
  1058    launch_thread(&err, &threads, walthread2_thread, (void*)1);
  1059    join_all_threads(&err, &threads);
  1060  
  1061    print_and_free_err(&err);
  1062  }
  1063  
  1064  static char *walthread3_thread(int iTid, void *pArg){
  1065    Error err = {0};                /* Error code and message */
  1066    Sqlite db = {0};                /* SQLite database connection */
  1067    i64 iNextWrite;                 /* Next value this thread will write */
  1068    int iArg = PTR2INT(pArg);
  1069  
  1070    opendb(&err, &db, "test.db", 0);
  1071    sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 10");
  1072  
  1073    iNextWrite = iArg+1;
  1074    while( 1 ){
  1075      i64 sum1;
  1076      i64 sum2;
  1077      int stop = 0;                 /* True to stop executing (test timed out) */
  1078  
  1079      while( 0==(stop = timetostop(&err)) ){
  1080        i64 iMax = execsql_i64(&err, &db, "SELECT max(cnt) FROM t1");
  1081        if( iMax+1==iNextWrite ) break;
  1082      }
  1083      if( stop ) break;
  1084  
  1085      sum1 = execsql_i64(&err, &db, "SELECT sum(cnt) FROM t1");
  1086      sum2 = execsql_i64(&err, &db, "SELECT sum(sum1) FROM t1");
  1087      execsql_i64(&err, &db, 
  1088          "INSERT INTO t1 VALUES(:iNextWrite, :iSum1, :iSum2)",
  1089          &iNextWrite, &sum1, &sum2
  1090      );
  1091      integrity_check(&err, &db);
  1092  
  1093      iNextWrite += WALTHREAD3_NTHREAD;
  1094    }
  1095  
  1096    closedb(&err, &db);
  1097    print_and_free_err(&err);
  1098    return 0;
  1099  }
  1100  
  1101  static void walthread3(int nMs){
  1102    Error err = {0};
  1103    Sqlite db = {0};
  1104    Threadset threads = {0};
  1105    int i;
  1106  
  1107    opendb(&err, &db, "test.db", 1);
  1108    sql_script(&err, &db, 
  1109        "PRAGMA journal_mode = WAL;"
  1110        "CREATE TABLE t1(cnt PRIMARY KEY, sum1, sum2);"
  1111        "CREATE INDEX i1 ON t1(sum1);"
  1112        "CREATE INDEX i2 ON t1(sum2);"
  1113        "INSERT INTO t1 VALUES(0, 0, 0);"
  1114    );
  1115    closedb(&err, &db);
  1116  
  1117    setstoptime(&err, nMs);
  1118    for(i=0; i<WALTHREAD3_NTHREAD; i++){
  1119      launch_thread(&err, &threads, walthread3_thread, INT2PTR(i));
  1120    }
  1121    join_all_threads(&err, &threads);
  1122  
  1123    print_and_free_err(&err);
  1124  }
  1125  
  1126  static char *walthread4_reader_thread(int iTid, void *pArg){
  1127    Error err = {0};                /* Error code and message */
  1128    Sqlite db = {0};                /* SQLite database connection */
  1129  
  1130    opendb(&err, &db, "test.db", 0);
  1131    while( !timetostop(&err) ){
  1132      integrity_check(&err, &db);
  1133    }
  1134    closedb(&err, &db);
  1135  
  1136    print_and_free_err(&err);
  1137    return 0;
  1138  }
  1139  
  1140  static char *walthread4_writer_thread(int iTid, void *pArg){
  1141    Error err = {0};                /* Error code and message */
  1142    Sqlite db = {0};                /* SQLite database connection */
  1143    i64 iRow = 1;
  1144  
  1145    opendb(&err, &db, "test.db", 0);
  1146    sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 15;");
  1147    while( !timetostop(&err) ){
  1148      execsql_i64(
  1149          &err, &db, "REPLACE INTO t1 VALUES(:iRow, randomblob(300))", &iRow
  1150      );
  1151      iRow++;
  1152      if( iRow==10 ) iRow = 0;
  1153    }
  1154    closedb(&err, &db);
  1155  
  1156    print_and_free_err(&err);
  1157    return 0;
  1158  }
  1159  
  1160  static void walthread4(int nMs){
  1161    Error err = {0};
  1162    Sqlite db = {0};
  1163    Threadset threads = {0};
  1164  
  1165    opendb(&err, &db, "test.db", 1);
  1166    sql_script(&err, &db, 
  1167        "PRAGMA journal_mode = WAL;"
  1168        "CREATE TABLE t1(a INTEGER PRIMARY KEY, b UNIQUE);"
  1169    );
  1170    closedb(&err, &db);
  1171  
  1172    setstoptime(&err, nMs);
  1173    launch_thread(&err, &threads, walthread4_reader_thread, 0);
  1174    launch_thread(&err, &threads, walthread4_writer_thread, 0);
  1175    join_all_threads(&err, &threads);
  1176  
  1177    print_and_free_err(&err);
  1178  }
  1179  
  1180  static char *walthread5_thread(int iTid, void *pArg){
  1181    Error err = {0};                /* Error code and message */
  1182    Sqlite db = {0};                /* SQLite database connection */
  1183    i64 nRow;
  1184  
  1185    opendb(&err, &db, "test.db", 0);
  1186    nRow = execsql_i64(&err, &db, "SELECT count(*) FROM t1");
  1187    closedb(&err, &db);
  1188  
  1189    if( nRow!=65536 ) test_error(&err, "Bad row count: %d", (int)nRow);
  1190    print_and_free_err(&err);
  1191    return 0;
  1192  }
  1193  static void walthread5(int nMs){
  1194    Error err = {0};
  1195    Sqlite db = {0};
  1196    Threadset threads = {0};
  1197  
  1198    opendb(&err, &db, "test.db", 1);
  1199    sql_script(&err, &db, 
  1200        "PRAGMA wal_autocheckpoint = 0;"
  1201        "PRAGMA page_size = 1024;"
  1202        "PRAGMA journal_mode = WAL;"
  1203        "CREATE TABLE t1(x);"
  1204        "BEGIN;"
  1205        "INSERT INTO t1 VALUES(randomblob(900));"
  1206        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*     2 */"
  1207        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*     4 */"
  1208        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*     8 */"
  1209        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*    16 */"
  1210        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*    32 */"
  1211        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*    64 */"
  1212        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*   128 */"
  1213        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*   256 */"
  1214        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*   512 */"
  1215        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  1024 */"
  1216        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  2048 */"
  1217        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  4096 */"
  1218        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /*  8192 */"
  1219        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /* 16384 */"
  1220        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /* 32768 */"
  1221        "INSERT INTO t1 SELECT randomblob(900) FROM t1;      /* 65536 */"
  1222        "COMMIT;"
  1223    );
  1224    filecopy(&err, "test.db", "test_sv.db");
  1225    filecopy(&err, "test.db-wal", "test_sv.db-wal");
  1226    closedb(&err, &db);
  1227  
  1228    filecopy(&err, "test_sv.db", "test.db");
  1229    filecopy(&err, "test_sv.db-wal", "test.db-wal");
  1230  
  1231    if( err.rc==SQLITE_OK ){
  1232      printf("  WAL file is %d bytes,", (int)filesize(&err,"test.db-wal"));
  1233      printf(" DB file is %d.\n", (int)filesize(&err,"test.db"));
  1234    }
  1235  
  1236    setstoptime(&err, nMs);
  1237    launch_thread(&err, &threads, walthread5_thread, 0);
  1238    launch_thread(&err, &threads, walthread5_thread, 0);
  1239    launch_thread(&err, &threads, walthread5_thread, 0);
  1240    launch_thread(&err, &threads, walthread5_thread, 0);
  1241    launch_thread(&err, &threads, walthread5_thread, 0);
  1242    join_all_threads(&err, &threads);
  1243  
  1244    if( err.rc==SQLITE_OK ){
  1245      printf("  WAL file is %d bytes,", (int)filesize(&err,"test.db-wal"));
  1246      printf(" DB file is %d.\n", (int)filesize(&err,"test.db"));
  1247    }
  1248  
  1249    print_and_free_err(&err);
  1250  }
  1251  
  1252  /*------------------------------------------------------------------------
  1253  ** Test case "cgt_pager_1"
  1254  */
  1255  #define CALLGRINDTEST1_NROW 10000
  1256  static void cgt_pager_1_populate(Error *pErr, Sqlite *pDb){
  1257    const char *zInsert = "INSERT INTO t1 VALUES(:iRow, zeroblob(:iBlob))";
  1258    i64 iRow;
  1259    sql_script(pErr, pDb, "BEGIN");
  1260    for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
  1261      i64 iBlob = 600 + (iRow%300);
  1262      execsql(pErr, pDb, zInsert, &iRow, &iBlob);
  1263    }
  1264    sql_script(pErr, pDb, "COMMIT");
  1265  }
  1266  static void cgt_pager_1_update(Error *pErr, Sqlite *pDb){
  1267    const char *zUpdate = "UPDATE t1 SET b = zeroblob(:iBlob) WHERE a = :iRow";
  1268    i64 iRow;
  1269    sql_script(pErr, pDb, "BEGIN");
  1270    for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
  1271      i64 iBlob = 600 + ((iRow+100)%300);
  1272      execsql(pErr, pDb, zUpdate, &iBlob, &iRow);
  1273    }
  1274    sql_script(pErr, pDb, "COMMIT");
  1275  }
  1276  static void cgt_pager_1_read(Error *pErr, Sqlite *pDb){
  1277    i64 iRow;
  1278    sql_script(pErr, pDb, "BEGIN");
  1279    for(iRow=1; iRow<=CALLGRINDTEST1_NROW; iRow++){
  1280      execsql(pErr, pDb, "SELECT * FROM t1 WHERE a = :iRow", &iRow);
  1281    }
  1282    sql_script(pErr, pDb, "COMMIT");
  1283  }
  1284  static void cgt_pager_1(int nMs){
  1285    void (*xSub)(Error *, Sqlite *);
  1286    Error err = {0};
  1287    Sqlite db = {0};
  1288  
  1289    opendb(&err, &db, "test.db", 1);
  1290    sql_script(&err, &db,
  1291        "PRAGMA cache_size = 2000;"
  1292        "PRAGMA page_size = 1024;"
  1293        "CREATE TABLE t1(a INTEGER PRIMARY KEY, b BLOB);"
  1294    );
  1295  
  1296    xSub = cgt_pager_1_populate; xSub(&err, &db);
  1297    xSub = cgt_pager_1_update;   xSub(&err, &db);
  1298    xSub = cgt_pager_1_read;     xSub(&err, &db);
  1299  
  1300    closedb(&err, &db);
  1301    print_and_free_err(&err);
  1302  }
  1303  
  1304  /*------------------------------------------------------------------------
  1305  ** Test case "dynamic_triggers"
  1306  **
  1307  **   Two threads executing statements that cause deeply nested triggers
  1308  **   to fire. And one thread busily creating and deleting triggers. This
  1309  **   is an attempt to find a bug reported to us.
  1310  */
  1311  
  1312  static char *dynamic_triggers_1(int iTid, void *pArg){
  1313    Error err = {0};                /* Error code and message */
  1314    Sqlite db = {0};                /* SQLite database connection */
  1315    int nDrop = 0;
  1316    int nCreate = 0;
  1317  
  1318    opendb(&err, &db, "test.db", 0);
  1319    while( !timetostop(&err) ){
  1320      int i;
  1321  
  1322      for(i=1; i<9; i++){
  1323        char *zSql = sqlite3_mprintf(
  1324          "CREATE TRIGGER itr%d BEFORE INSERT ON t%d BEGIN "
  1325            "INSERT INTO t%d VALUES(new.x, new.y);"
  1326          "END;", i, i, i+1
  1327        );
  1328        execsql(&err, &db, zSql);
  1329        sqlite3_free(zSql);
  1330        nCreate++;
  1331      }
  1332  
  1333      for(i=1; i<9; i++){
  1334        char *zSql = sqlite3_mprintf(
  1335          "CREATE TRIGGER dtr%d BEFORE DELETE ON t%d BEGIN "
  1336            "DELETE FROM t%d WHERE x = old.x; "
  1337          "END;", i, i, i+1
  1338        );
  1339        execsql(&err, &db, zSql);
  1340        sqlite3_free(zSql);
  1341        nCreate++;
  1342      }
  1343  
  1344      for(i=1; i<9; i++){
  1345        char *zSql = sqlite3_mprintf("DROP TRIGGER itr%d", i);
  1346        execsql(&err, &db, zSql);
  1347        sqlite3_free(zSql);
  1348        nDrop++;
  1349      }
  1350  
  1351      for(i=1; i<9; i++){
  1352        char *zSql = sqlite3_mprintf("DROP TRIGGER dtr%d", i);
  1353        execsql(&err, &db, zSql);
  1354        sqlite3_free(zSql);
  1355        nDrop++;
  1356      }
  1357    }
  1358    closedb(&err, &db);
  1359  
  1360    print_and_free_err(&err);
  1361    return sqlite3_mprintf("%d created, %d dropped", nCreate, nDrop);
  1362  }
  1363  
  1364  static char *dynamic_triggers_2(int iTid, void *pArg){
  1365    Error err = {0};                /* Error code and message */
  1366    Sqlite db = {0};                /* SQLite database connection */
  1367    i64 iVal = 0;
  1368    int nInsert = 0;
  1369    int nDelete = 0;
  1370  
  1371    opendb(&err, &db, "test.db", 0);
  1372    while( !timetostop(&err) ){
  1373      do {
  1374        iVal = (iVal+1)%100;
  1375        execsql(&err, &db, "INSERT INTO t1 VALUES(:iX, :iY+1)", &iVal, &iVal);
  1376        nInsert++;
  1377      } while( iVal );
  1378  
  1379      do {
  1380        iVal = (iVal+1)%100;
  1381        execsql(&err, &db, "DELETE FROM t1 WHERE x = :iX", &iVal);
  1382        nDelete++;
  1383      } while( iVal );
  1384    }
  1385    closedb(&err, &db);
  1386  
  1387    print_and_free_err(&err);
  1388    return sqlite3_mprintf("%d inserts, %d deletes", nInsert, nDelete);
  1389  }
  1390  
  1391  static void dynamic_triggers(int nMs){
  1392    Error err = {0};
  1393    Sqlite db = {0};
  1394    Threadset threads = {0};
  1395  
  1396    opendb(&err, &db, "test.db", 1);
  1397    sql_script(&err, &db, 
  1398        "PRAGMA page_size = 1024;"
  1399        "PRAGMA journal_mode = WAL;"
  1400        "CREATE TABLE t1(x, y);"
  1401        "CREATE TABLE t2(x, y);"
  1402        "CREATE TABLE t3(x, y);"
  1403        "CREATE TABLE t4(x, y);"
  1404        "CREATE TABLE t5(x, y);"
  1405        "CREATE TABLE t6(x, y);"
  1406        "CREATE TABLE t7(x, y);"
  1407        "CREATE TABLE t8(x, y);"
  1408        "CREATE TABLE t9(x, y);"
  1409    );
  1410    closedb(&err, &db);
  1411  
  1412    setstoptime(&err, nMs);
  1413  
  1414    sqlite3_enable_shared_cache(1);
  1415    launch_thread(&err, &threads, dynamic_triggers_2, 0);
  1416    launch_thread(&err, &threads, dynamic_triggers_2, 0);
  1417  
  1418    sleep(2);
  1419    sqlite3_enable_shared_cache(0);
  1420  
  1421    launch_thread(&err, &threads, dynamic_triggers_2, 0);
  1422    launch_thread(&err, &threads, dynamic_triggers_1, 0);
  1423  
  1424    join_all_threads(&err, &threads);
  1425  
  1426    print_and_free_err(&err);
  1427  }
  1428  
  1429  
  1430  
  1431  #include "tt3_checkpoint.c"
  1432  #include "tt3_index.c"
  1433  #include "tt3_lookaside1.c"
  1434  #include "tt3_vacuum.c"
  1435  #include "tt3_stress.c"
  1436  #include "tt3_shared.c"
  1437  
  1438  int main(int argc, char **argv){
  1439    struct ThreadTest {
  1440      void (*xTest)(int);   /* Routine for running this test */
  1441      const char *zTest;    /* Name of this test */
  1442      int nMs;              /* How long to run this test, in milliseconds */
  1443    } aTest[] = {
  1444      { walthread1, "walthread1", 20000 },
  1445      { walthread2, "walthread2", 20000 },
  1446      { walthread3, "walthread3", 20000 },
  1447      { walthread4, "walthread4", 20000 },
  1448      { walthread5, "walthread5",  1000 },
  1449      
  1450      { cgt_pager_1,      "cgt_pager_1", 0 },
  1451      { dynamic_triggers, "dynamic_triggers", 20000 },
  1452  
  1453      { checkpoint_starvation_1, "checkpoint_starvation_1", 10000 },
  1454      { checkpoint_starvation_2, "checkpoint_starvation_2", 10000 },
  1455  
  1456      { create_drop_index_1, "create_drop_index_1", 10000 },
  1457      { lookaside1,          "lookaside1", 10000 },
  1458      { vacuum1,             "vacuum1", 10000 },
  1459      { stress1,             "stress1", 10000 },
  1460      { stress2,             "stress2", 60000 },
  1461      { shared1,             "shared1", 10000 },
  1462    };
  1463    static char *substArgv[] = { 0, "*", 0 };
  1464    int i, iArg;
  1465    int nTestfound = 0;
  1466  
  1467    sqlite3_config(SQLITE_CONFIG_MULTITHREAD);
  1468    if( argc<2 ){
  1469      argc = 2;
  1470      argv = substArgv;
  1471    }
  1472  
  1473    /* Loop through the command-line arguments to ensure that each argument
  1474    ** selects at least one test. If not, assume there is a typo on the 
  1475    ** command-line and bail out with the usage message.  */
  1476    for(iArg=1; iArg<argc; iArg++){
  1477      const char *zArg = argv[iArg];
  1478      if( zArg[0]=='-' ){
  1479        if( sqlite3_stricmp(zArg, "-multiplexor")==0 ){
  1480          /* Install the multiplexor VFS as the default */
  1481          int rc = sqlite3_multiplex_initialize(0, 1);
  1482          if( rc!=SQLITE_OK ){
  1483            fprintf(stderr, "Failed to install multiplexor VFS (%d)\n", rc);
  1484            return 253;
  1485          }
  1486        }
  1487        else {
  1488          goto usage;
  1489        }
  1490  
  1491        continue;
  1492      }
  1493  
  1494      for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
  1495        if( sqlite3_strglob(zArg, aTest[i].zTest)==0 ) break;
  1496      }
  1497      if( i>=sizeof(aTest)/sizeof(aTest[0]) ) goto usage;   
  1498    }
  1499  
  1500    for(iArg=1; iArg<argc; iArg++){
  1501      if( argv[iArg][0]=='-' ) continue;
  1502      for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
  1503        char const *z = aTest[i].zTest;
  1504        if( sqlite3_strglob(argv[iArg],z)==0 ){
  1505          printf("Running %s for %d seconds...\n", z, aTest[i].nMs/1000);
  1506          fflush(stdout);
  1507          aTest[i].xTest(aTest[i].nMs);
  1508          nTestfound++;
  1509        }
  1510      }
  1511    }
  1512    if( nTestfound==0 ) goto usage;
  1513  
  1514    printf("%d errors out of %d tests\n", nGlobalErr, nTestfound);
  1515    return (nGlobalErr>0 ? 255 : 0);
  1516  
  1517   usage:
  1518    printf("Usage: %s [-multiplexor] [testname|testprefix*]...\n", argv[0]);
  1519    printf("Available tests are:\n");
  1520    for(i=0; i<sizeof(aTest)/sizeof(aTest[0]); i++){
  1521      printf("   %s\n", aTest[i].zTest);
  1522    }
  1523  
  1524    return 254;
  1525  }