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