AryaWu/sqlite
0
1/*2** 2010-07-223**4** The author disclaims copyright to this source code. In place of5** 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 the14** SQLite library. It can be compiled to an executable on unix using the15** following command:16**17** gcc -O2 threadtest3.c sqlite3.c -ldl -lpthread -lm18**19** Even though threadtest3.c is the only C source code file mentioned on20** the compiler command-line, #include macros are used to pull in additional21** C code files named "tt3_*.c".22**23** After compiling, run this program with an optional argument telling24** which test to run. All tests are run if no argument is given. The25** argument can be a glob pattern to match multiple tests. Examples:26**27** ./a.out -- Run all tests28** ./a.out walthread3 -- Run the "walthread3" test29** ./a.out 'wal*' -- Run all of the wal* tests30** ./a.out --help -- List all available tests31**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 82#ifdef _WIN3283# include <stdio.h>84# include <string.h>85# include <assert.h>86# include <process.h>87# include <windows.h>88# include <sys/types.h> 89# include <sys/stat.h> 90# include <errno.h>91# include <fcntl.h>92# include <io.h>93#else94# include <unistd.h>95# include <stdio.h>96# include <pthread.h>97# include <assert.h>98# include <sys/types.h> 99# include <sys/stat.h> 100# include <string.h>101# include <fcntl.h>102# include <errno.h>103 104# define O_BINARY 0105#endif106 107#include "test_multiplex.h"108 109/* Required to link test_multiplex.c */110#ifndef SQLITE_OMIT_WSD111int sqlite3PendingByte = 0x40000000;112#endif113 114/*115 * This code implements the MD5 message-digest algorithm.116 * The algorithm is due to Ron Rivest. This code was117 * written by Colin Plumb in 1993, no copyright is claimed.118 * This code is in the public domain; do with it what you wish.119 *120 * Equivalent code is available from RSA Data Security, Inc.121 * This code has been tested against that, and is equivalent,122 * except that you don't need to include two pages of legalese123 * with every copy.124 *125 * To compute the message digest of a chunk of bytes, declare an126 * MD5Context structure, pass it to MD5Init, call MD5Update as127 * needed on buffers full of bytes, and then call MD5Final, which128 * will fill a supplied 16-byte array with the digest.129 */130 131/*132 * If compiled on a machine that doesn't have a 32-bit integer,133 * you just set "uint32" to the appropriate datatype for an134 * unsigned 32-bit integer. For example:135 *136 * cc -Duint32='unsigned long' md5.c137 *138 */139#ifndef uint32140# define uint32 unsigned int141#endif142 143struct MD5Context {144 int isInit;145 uint32 buf[4];146 uint32 bits[2];147 union {148 unsigned char in[64];149 uint32 in32[16];150 } u;151};152typedef struct MD5Context MD5Context;153 154/*155 * Note: this code is harmless on little-endian machines.156 */157static void byteReverse (unsigned char *buf, unsigned longs){158 uint32 t;159 do {160 t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 |161 ((unsigned)buf[1]<<8 | buf[0]);162 *(uint32 *)buf = t;163 buf += 4;164 } while (--longs);165}166/* The four core functions - F1 is optimized somewhat */167 168/* #define F1(x, y, z) (x & y | ~x & z) */169#define F1(x, y, z) (z ^ (x & (y ^ z)))170#define F2(x, y, z) F1(z, x, y)171#define F3(x, y, z) (x ^ y ^ z)172#define F4(x, y, z) (y ^ (x | ~z))173 174/* This is the central step in the MD5 algorithm. */175#define MD5STEP(f, w, x, y, z, data, s) \176 ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )177 178/*179 * The core of the MD5 algorithm, this alters an existing MD5 hash to180 * reflect the addition of 16 longwords of new data. MD5Update blocks181 * the data and converts bytes into longwords for this routine.182 */183static void MD5Transform(uint32 buf[4], const uint32 in[16]){184 register uint32 a, b, c, d;185 186 a = buf[0];187 b = buf[1];188 c = buf[2];189 d = buf[3];190 191 MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7);192 MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12);193 MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17);194 MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22);195 MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7);196 MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12);197 MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17);198 MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22);199 MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7);200 MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12);201 MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17);202 MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22);203 MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7);204 MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12);205 MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17);206 MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22);207 208 MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5);209 MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9);210 MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14);211 MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20);212 MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5);213 MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9);214 MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14);215 MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20);216 MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5);217 MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9);218 MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14);219 MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20);220 MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5);221 MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9);222 MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14);223 MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20);224 225 MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4);226 MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11);227 MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16);228 MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23);229 MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4);230 MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11);231 MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16);232 MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23);233 MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4);234 MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11);235 MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16);236 MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23);237 MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4);238 MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11);239 MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16);240 MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23);241 242 MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6);243 MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10);244 MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15);245 MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21);246 MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6);247 MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10);248 MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15);249 MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21);250 MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6);251 MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10);252 MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15);253 MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21);254 MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6);255 MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10);256 MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15);257 MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21);258 259 buf[0] += a;260 buf[1] += b;261 buf[2] += c;262 buf[3] += d;263}264 265/*266 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious267 * initialization constants.268 */269static void MD5Init(MD5Context *ctx){270 ctx->isInit = 1;271 ctx->buf[0] = 0x67452301;272 ctx->buf[1] = 0xefcdab89;273 ctx->buf[2] = 0x98badcfe;274 ctx->buf[3] = 0x10325476;275 ctx->bits[0] = 0;276 ctx->bits[1] = 0;277}278 279/*280 * Update context to reflect the concatenation of another buffer full281 * of bytes.282 */283static 284void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){285 uint32 t;286 287 /* Update bitcount */288 289 t = ctx->bits[0];290 if ((ctx->bits[0] = t + ((uint32)len << 3)) < t)291 ctx->bits[1]++; /* Carry from low to high */292 ctx->bits[1] += len >> 29;293 294 t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */295 296 /* Handle any leading odd-sized chunks */297 298 if ( t ) {299 unsigned char *p = (unsigned char *)ctx->u.in + t;300 301 t = 64-t;302 if (len < t) {303 memcpy(p, buf, len);304 return;305 }306 memcpy(p, buf, t);307 byteReverse(ctx->u.in, 16);308 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);309 buf += t;310 len -= t;311 }312 313 /* Process data in 64-byte chunks */314 315 while (len >= 64) {316 memcpy(ctx->u.in, buf, 64);317 byteReverse(ctx->u.in, 16);318 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);319 buf += 64;320 len -= 64;321 }322 323 /* Handle any remaining bytes of data. */324 325 memcpy(ctx->u.in, buf, len);326}327 328/*329 * Final wrapup - pad to 64-byte boundary with the bit pattern 330 * 1 0* (64-bit count of bits processed, MSB-first)331 */332static void MD5Final(unsigned char digest[16], MD5Context *ctx){333 unsigned count;334 unsigned char *p;335 336 /* Compute number of bytes mod 64 */337 count = (ctx->bits[0] >> 3) & 0x3F;338 339 /* Set the first char of padding to 0x80. This is safe since there is340 always at least one byte free */341 p = ctx->u.in + count;342 *p++ = 0x80;343 344 /* Bytes of padding needed to make 64 bytes */345 count = 64 - 1 - count;346 347 /* Pad out to 56 mod 64 */348 if (count < 8) {349 /* Two lots of padding: Pad the first block to 64 bytes */350 memset(p, 0, count);351 byteReverse(ctx->u.in, 16);352 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);353 354 /* Now fill the next block with 56 bytes */355 memset(ctx->u.in, 0, 56);356 } else {357 /* Pad block to 56 bytes */358 memset(p, 0, count-8);359 }360 byteReverse(ctx->u.in, 14);361 362 /* Append length in bits and transform */363 ctx->u.in32[14] = ctx->bits[0];364 ctx->u.in32[15] = ctx->bits[1];365 366 MD5Transform(ctx->buf, (uint32 *)ctx->u.in);367 byteReverse((unsigned char *)ctx->buf, 4);368 memcpy(digest, ctx->buf, 16);369 memset(ctx, 0, sizeof(*ctx)); /* In case it is sensitive */370}371 372/*373** Convert a 128-bit MD5 digest into a 32-digit base-16 number.374*/375static void MD5DigestToBase16(unsigned char *digest, char *zBuf){376 static char const zEncode[] = "0123456789abcdef";377 int i, j;378 379 for(j=i=0; i<16; i++){380 int a = digest[i];381 zBuf[j++] = zEncode[(a>>4)&0xf];382 zBuf[j++] = zEncode[a & 0xf];383 }384 zBuf[j] = 0;385}386 387/*388** During testing, the special md5sum() aggregate function is available.389** inside SQLite. The following routines implement that function.390*/391static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){392 MD5Context *p;393 int i;394 if( argc<1 ) return;395 p = sqlite3_aggregate_context(context, sizeof(*p));396 if( p==0 ) return;397 if( !p->isInit ){398 MD5Init(p);399 }400 for(i=0; i<argc; i++){401 const char *zData = (char*)sqlite3_value_text(argv[i]);402 if( zData ){403 MD5Update(p, (unsigned char*)zData, strlen(zData));404 }405 }406}407static void md5finalize(sqlite3_context *context){408 MD5Context *p;409 unsigned char digest[16];410 char zBuf[33];411 p = sqlite3_aggregate_context(context, sizeof(*p));412 MD5Final(digest,p);413 MD5DigestToBase16(digest, zBuf);414 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);415}416 417/*418** End of copied md5sum() code.419**************************************************************************/420 421typedef sqlite3_int64 i64;422 423typedef struct Error Error;424typedef struct Sqlite Sqlite;425typedef struct Statement Statement;426 427typedef struct Threadset Threadset;428typedef struct Thread Thread;429 430/* Total number of errors in this process so far. */431static int nGlobalErr = 0;432 433struct Error {434 int rc;435 int iLine;436 char *zErr;437};438 439struct Sqlite {440 sqlite3 *db; /* Database handle */441 Statement *pCache; /* Linked list of cached statements */442 int nText; /* Size of array at aText[] */443 char **aText; /* Stored text results */444};445 446struct Statement {447 sqlite3_stmt *pStmt; /* Pre-compiled statement handle */448 Statement *pNext; /* Next statement in linked-list */449};450 451struct Thread {452 int iTid; /* Thread number within test */453 void* pArg; /* Pointer argument passed by caller */454 455#ifdef _WIN32456 uintptr_t winTid; /* Thread handle */457#else458 pthread_t tid; /* Thread id */459#endif460 char *(*xProc)(int, void*); /* Thread main proc */461 char *zRes; /* Value returned by xProc */462 Thread *pNext; /* Next in this list of threads */463};464 465struct Threadset {466 int iMaxTid; /* Largest iTid value allocated so far */467 Thread *pThread; /* Linked list of threads */468};469 470static void free_err(Error *p){471 sqlite3_free(p->zErr);472 p->zErr = 0;473 p->rc = 0;474}475 476static void print_err(Error *p){477 if( p->rc!=SQLITE_OK ){478 int isWarn = 0;479 if( p->rc==SQLITE_SCHEMA ) isWarn = 1;480 if( sqlite3_strglob("* - no such table: *",p->zErr)==0 ) isWarn = 1;481 printf("%s: (%d) \"%s\" at line %d\n", isWarn ? "Warning" : "Error",482 p->rc, p->zErr, p->iLine);483 if( !isWarn ) nGlobalErr++;484 fflush(stdout);485 }486}487 488static void print_and_free_err(Error *p){489 print_err(p);490 free_err(p);491}492 493static void system_error(Error *pErr, int iSys){494 pErr->rc = iSys;495#if _WIN32496 pErr->zErr = sqlite3_mprintf("%s", strerror(iSys));497#else498 pErr->zErr = (char *)sqlite3_malloc(512);499 strerror_r(iSys, pErr->zErr, 512);500 pErr->zErr[511] = '\0';501#endif502}503 504static void sqlite_error(505 Error *pErr, 506 Sqlite *pDb, 507 const char *zFunc508){509 pErr->rc = sqlite3_errcode(pDb->db);510 pErr->zErr = sqlite3_mprintf(511 "sqlite3_%s() - %s (%d)", zFunc, sqlite3_errmsg(pDb->db),512 sqlite3_extended_errcode(pDb->db)513 );514}515 516static void test_error_x(517 Error *pErr,518 char *zErr519){520 if( pErr->rc==SQLITE_OK ){521 pErr->rc = 1;522 pErr->zErr = zErr;523 }else{524 sqlite3_free(zErr);525 }526}527 528static void clear_error_x(529 Error *pErr,530 int rc531){532 if( pErr->rc==rc ){533 pErr->rc = SQLITE_OK;534 sqlite3_free(pErr->zErr);535 pErr->zErr = 0;536 }537}538 539static int busyhandler(void *pArg, int n){540 sqlite3_sleep(10);541 return 1;542}543 544static void opendb_x(545 Error *pErr, /* IN/OUT: Error code */546 Sqlite *pDb, /* OUT: Database handle */547 const char *zFile, /* Database file name */548 int bDelete /* True to delete db file before opening */549){550 if( pErr->rc==SQLITE_OK ){551 int rc;552 int flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_URI;553 if( bDelete ) unlink(zFile);554 rc = sqlite3_open_v2(zFile, &pDb->db, flags, 0);555 if( rc ){556 sqlite_error(pErr, pDb, "open");557 sqlite3_close(pDb->db);558 pDb->db = 0;559 }else{560 sqlite3_create_function(561 pDb->db, "md5sum", -1, SQLITE_UTF8, 0, 0, md5step, md5finalize562 );563 sqlite3_busy_handler(pDb->db, busyhandler, 0);564 sqlite3_exec(pDb->db, "PRAGMA synchronous=OFF", 0, 0, 0);565 }566 }567}568 569static void closedb_x(570 Error *pErr, /* IN/OUT: Error code */571 Sqlite *pDb /* OUT: Database handle */572){573 int rc;574 int i;575 Statement *pIter;576 Statement *pNext;577 for(pIter=pDb->pCache; pIter; pIter=pNext){578 pNext = pIter->pNext;579 sqlite3_finalize(pIter->pStmt);580 sqlite3_free(pIter);581 }582 for(i=0; i<pDb->nText; i++){583 sqlite3_free(pDb->aText[i]);584 }585 sqlite3_free(pDb->aText);586 rc = sqlite3_close(pDb->db);587 if( rc && pErr->rc==SQLITE_OK ){588 pErr->zErr = sqlite3_mprintf("%s", sqlite3_errmsg(pDb->db));589 }590 memset(pDb, 0, sizeof(Sqlite));591}592 593static void sql_script_x(594 Error *pErr, /* IN/OUT: Error code */595 Sqlite *pDb, /* Database handle */596 const char *zSql /* SQL script to execute */597){598 if( pErr->rc==SQLITE_OK ){599 pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);600 }601}602 603static void sql_script_printf_x(604 Error *pErr, /* IN/OUT: Error code */605 Sqlite *pDb, /* Database handle */606 const char *zFormat, /* SQL printf format string */607 ... /* Printf args */608){609 va_list ap; /* ... printf arguments */610 va_start(ap, zFormat);611 if( pErr->rc==SQLITE_OK ){612 char *zSql = sqlite3_vmprintf(zFormat, ap);613 pErr->rc = sqlite3_exec(pDb->db, zSql, 0, 0, &pErr->zErr);614 sqlite3_free(zSql);615 }616 va_end(ap);617}618 619static Statement *getSqlStatement(620 Error *pErr, /* IN/OUT: Error code */621 Sqlite *pDb, /* Database handle */622 const char *zSql /* SQL statement */623){624 Statement *pRet;625 int rc;626 627 for(pRet=pDb->pCache; pRet; pRet=pRet->pNext){628 if( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) ){629 return pRet;630 }631 }632 633 pRet = sqlite3_malloc(sizeof(Statement));634 rc = sqlite3_prepare_v2(pDb->db, zSql, -1, &pRet->pStmt, 0);635 if( rc!=SQLITE_OK ){636 sqlite_error(pErr, pDb, "prepare_v2");637 return 0;638 }639 assert( 0==strcmp(sqlite3_sql(pRet->pStmt), zSql) );640 641 pRet->pNext = pDb->pCache;642 pDb->pCache = pRet;643 return pRet;644}645 646static sqlite3_stmt *getAndBindSqlStatement(647 Error *pErr, /* IN/OUT: Error code */648 Sqlite *pDb, /* Database handle */649 va_list ap /* SQL followed by parameters */650){651 Statement *pStatement; /* The SQLite statement wrapper */652 sqlite3_stmt *pStmt; /* The SQLite statement to return */653 int i; /* Used to iterate through parameters */654 655 pStatement = getSqlStatement(pErr, pDb, va_arg(ap, const char *));656 if( !pStatement ) return 0;657 pStmt = pStatement->pStmt;658 for(i=1; i<=sqlite3_bind_parameter_count(pStmt); i++){659 const char *zName = sqlite3_bind_parameter_name(pStmt, i);660 void * pArg = va_arg(ap, void*);661 662 switch( zName[1] ){663 case 'i':664 sqlite3_bind_int64(pStmt, i, *(i64 *)pArg);665 break;666 667 default:668 pErr->rc = 1;669 pErr->zErr = sqlite3_mprintf("Cannot discern type: \"%s\"", zName);670 pStmt = 0;671 break;672 }673 }674 675 return pStmt;676}677 678static i64 execsql_i64_x(679 Error *pErr, /* IN/OUT: Error code */680 Sqlite *pDb, /* Database handle */681 ... /* SQL and pointers to parameter values */682){683 i64 iRet = 0;684 if( pErr->rc==SQLITE_OK ){685 sqlite3_stmt *pStmt; /* SQL statement to execute */686 va_list ap; /* ... arguments */687 va_start(ap, pDb);688 pStmt = getAndBindSqlStatement(pErr, pDb, ap);689 if( pStmt ){690 int first = 1;691 while( SQLITE_ROW==sqlite3_step(pStmt) ){692 if( first && sqlite3_column_count(pStmt)>0 ){693 iRet = sqlite3_column_int64(pStmt, 0);694 }695 first = 0;696 }697 if( SQLITE_OK!=sqlite3_reset(pStmt) ){698 sqlite_error(pErr, pDb, "reset");699 }700 }701 va_end(ap);702 }703 return iRet;704}705 706static char * execsql_text_x(707 Error *pErr, /* IN/OUT: Error code */708 Sqlite *pDb, /* Database handle */709 int iSlot, /* Db handle slot to store text in */710 ... /* SQL and pointers to parameter values */711){712 char *zRet = 0;713 714 if( iSlot>=pDb->nText ){715 int nByte = sizeof(char *)*(iSlot+1);716 pDb->aText = (char **)sqlite3_realloc(pDb->aText, nByte);717 memset(&pDb->aText[pDb->nText], 0, sizeof(char*)*(iSlot+1-pDb->nText));718 pDb->nText = iSlot+1;719 }720 721 if( pErr->rc==SQLITE_OK ){722 sqlite3_stmt *pStmt; /* SQL statement to execute */723 va_list ap; /* ... arguments */724 va_start(ap, iSlot);725 pStmt = getAndBindSqlStatement(pErr, pDb, ap);726 if( pStmt ){727 int first = 1;728 while( SQLITE_ROW==sqlite3_step(pStmt) ){729 if( first && sqlite3_column_count(pStmt)>0 ){730 zRet = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 0));731 sqlite3_free(pDb->aText[iSlot]);732 pDb->aText[iSlot] = zRet;733 }734 first = 0;735 }736 if( SQLITE_OK!=sqlite3_reset(pStmt) ){737 sqlite_error(pErr, pDb, "reset");738 }739 }740 va_end(ap);741 }742 743 return zRet;744}745 746static void integrity_check_x(747 Error *pErr, /* IN/OUT: Error code */748 Sqlite *pDb /* Database handle */749){750 if( pErr->rc==SQLITE_OK ){751 Statement *pStatement; /* Statement to execute */752 char *zErr = 0; /* Integrity check error */753 754 pStatement = getSqlStatement(pErr, pDb, "PRAGMA integrity_check");755 if( pStatement ){756 sqlite3_stmt *pStmt = pStatement->pStmt;757 while( SQLITE_ROW==sqlite3_step(pStmt) ){758 const char *z = (const char*)sqlite3_column_text(pStmt, 0);759 if( strcmp(z, "ok") ){760 if( zErr==0 ){761 zErr = sqlite3_mprintf("%s", z);762 }else{763 zErr = sqlite3_mprintf("%z\n%s", zErr, z);764 }765 }766 }767 sqlite3_reset(pStmt);768 769 if( zErr ){770 pErr->zErr = zErr;771 pErr->rc = 1;772 }773 }774 }775}776 777#ifdef _WIN32778static unsigned __stdcall launch_thread_main(void *pArg){779 Thread *p = (Thread *)pArg;780 p->zRes = p->xProc(p->iTid, p->pArg);781 _endthreadex(0);782 return 0; /* NOT REACHED */783}784#else785static void *launch_thread_main(void *pArg){786 Thread *p = (Thread *)pArg;787 p->zRes = p->xProc(p->iTid, p->pArg);788 return 0;789}790#endif791 792static void launch_thread_x(793 Error *pErr, /* IN/OUT: Error code */794 Threadset *pThreads, /* Thread set */795 char *(*xProc)(int, void*), /* Proc to run */796 void *pArg /* Argument passed to thread proc */797){798 if( pErr->rc==SQLITE_OK ){799 int iTid = ++pThreads->iMaxTid;800 Thread *p;801 int rc;802 803 p = (Thread *)sqlite3_malloc(sizeof(Thread));804 memset(p, 0, sizeof(Thread));805 p->iTid = iTid;806 p->pArg = pArg;807 p->xProc = xProc;808 809#ifdef _WIN32810 rc = SQLITE_OK;811 p->winTid = _beginthreadex(0, 0, launch_thread_main, (void*)p, 0, 0);812 if( p->winTid==0 ) rc = errno ? errno : rc;813#else814 rc = pthread_create(&p->tid, NULL, launch_thread_main, (void *)p);815#endif816 if( rc!=0 ){817 system_error(pErr, rc);818 sqlite3_free(p);819 }else{820 p->pNext = pThreads->pThread;821 pThreads->pThread = p;822 }823 }824}825 826static void join_all_threads_x(827 Error *pErr, /* IN/OUT: Error code */828 Threadset *pThreads /* Thread set */829){830 Thread *p;831 Thread *pNext;832 for(p=pThreads->pThread; p; p=pNext){833#ifndef _WIN32834 void *ret;835#endif836 int rc;837 pNext = p->pNext;838 839#ifdef _WIN32840 do {841 rc = WaitForSingleObjectEx((HANDLE)p->winTid, INFINITE, TRUE);842 }while( rc==WAIT_IO_COMPLETION );843 CloseHandle((HANDLE)p->winTid);844#else845 rc = pthread_join(p->tid, &ret);846#endif847 848 if( rc!=0 ){849 if( pErr->rc==SQLITE_OK ) system_error(pErr, rc);850 }else{851 printf("Thread %d says: %s\n", p->iTid, (p->zRes==0 ? "..." : p->zRes));852 fflush(stdout);853 }854 sqlite3_free(p->zRes);855 sqlite3_free(p);856 }857 pThreads->pThread = 0;858}859 860#ifdef _WIN32861# define THREADTEST3_STAT _stat862#else863# define THREADTEST3_STAT stat864#endif865 866static i64 filesize_x(867 Error *pErr,868 const char *zFile869){870 i64 iRet = 0;871 if( pErr->rc==SQLITE_OK ){872 struct THREADTEST3_STAT sStat;873 if( THREADTEST3_STAT(zFile, &sStat) ){874 iRet = -1;875 }else{876 iRet = sStat.st_size;877 }878 }879 return iRet;880}881 882static void filecopy_x(883 Error *pErr,884 const char *zFrom,885 const char *zTo886){887 if( pErr->rc==SQLITE_OK ){888 i64 nByte = filesize_x(pErr, zFrom);889 if( nByte<0 ){890 test_error_x(pErr, sqlite3_mprintf("no such file: %s", zFrom));891 }else{892 i64 iOff;893 char aBuf[1024];894 int fd1;895 int fd2;896 unlink(zTo);897 898 fd1 = open(zFrom, O_RDONLY|O_BINARY);899 if( fd1<0 ){900 system_error(pErr, errno);901 return;902 }903 fd2 = open(zTo, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0644);904 if( fd2<0 ){905 system_error(pErr, errno);906 close(fd1);907 return;908 }909 910 iOff = 0;911 while( iOff<nByte ){912 int nCopy = sizeof(aBuf);913 if( nCopy+iOff>nByte ){914 nCopy = nByte - iOff;915 }916 if( nCopy!=read(fd1, aBuf, nCopy) ){917 system_error(pErr, errno);918 break;919 }920 if( nCopy!=write(fd2, aBuf, nCopy) ){921 system_error(pErr, errno);922 break;923 }924 iOff += nCopy;925 }926 927 close(fd1);928 close(fd2);929 }930 }931}932 933/* 934** Used by setstoptime() and timetostop().935*/936static double timelimit = 0.0;937 938static double currentTime(void){939 double t;940 static sqlite3_vfs *pTimelimitVfs = 0;941 if( pTimelimitVfs==0 ) pTimelimitVfs = sqlite3_vfs_find(0);942 if( pTimelimitVfs->iVersion>=2 && pTimelimitVfs->xCurrentTimeInt64!=0 ){943 sqlite3_int64 tm;944 pTimelimitVfs->xCurrentTimeInt64(pTimelimitVfs, &tm);945 t = tm/86400000.0;946 }else{947 pTimelimitVfs->xCurrentTime(pTimelimitVfs, &t);948 }949 return t;950}951 952static void setstoptime_x(953 Error *pErr, /* IN/OUT: Error code */954 int nMs /* Milliseconds until "stop time" */955){956 if( pErr->rc==SQLITE_OK ){957 double t = currentTime();958 timelimit = t + ((double)nMs)/(1000.0*60.0*60.0*24.0);959 }960}961 962static int timetostop_x(963 Error *pErr /* IN/OUT: Error code */964){965 int ret = 1;966 if( pErr->rc==SQLITE_OK ){967 double t = currentTime();968 ret = (t >= timelimit);969 }970 return ret;971}972 973 974/*************************************************************************975**************************************************************************976**************************************************************************977** End infrastructure. Begin tests.978*/979 980#define WALTHREAD1_NTHREAD 10981#define WALTHREAD3_NTHREAD 6982 983static char *walthread1_thread(int iTid, void *pArg){984 Error err = {0}; /* Error code and message */985 Sqlite db = {0}; /* SQLite database connection */986 int nIter = 0; /* Iterations so far */987 988 opendb(&err, &db, "test.db", 0);989 while( !timetostop(&err) ){990 const char *azSql[] = {991 "SELECT md5sum(x) FROM t1 WHERE rowid != (SELECT max(rowid) FROM t1)",992 "SELECT x FROM t1 WHERE rowid = (SELECT max(rowid) FROM t1)",993 };994 char *z1, *z2, *z3;995 996 execsql(&err, &db, "BEGIN");997 integrity_check(&err, &db);998 z1 = execsql_text(&err, &db, 1, azSql[0]);999 z2 = execsql_text(&err, &db, 2, azSql[1]);1000 z3 = execsql_text(&err, &db, 3, azSql[0]);1001 execsql(&err, &db, "COMMIT");1002 1003 if( strcmp(z1, z2) || strcmp(z1, z3) ){1004 test_error(&err, "Failed read: %s %s %s", z1, z2, z3);1005 }1006 1007 sql_script(&err, &db,1008 "BEGIN;"1009 "INSERT INTO t1 VALUES(randomblob(100));"1010 "INSERT INTO t1 VALUES(randomblob(100));"1011 "INSERT INTO t1 SELECT md5sum(x) FROM t1;"1012 "COMMIT;"1013 );1014 nIter++;1015 }1016 closedb(&err, &db);1017 1018 print_and_free_err(&err);1019 return sqlite3_mprintf("%d iterations", nIter);1020}1021 1022static char *walthread1_ckpt_thread(int iTid, void *pArg){1023 Error err = {0}; /* Error code and message */1024 Sqlite db = {0}; /* SQLite database connection */1025 int nCkpt = 0; /* Checkpoints so far */1026 1027 opendb(&err, &db, "test.db", 0);1028 while( !timetostop(&err) ){1029 sqlite3_sleep(500);1030 execsql(&err, &db, "PRAGMA wal_checkpoint");1031 if( err.rc==SQLITE_OK ) nCkpt++;1032 clear_error(&err, SQLITE_BUSY);1033 }1034 closedb(&err, &db);1035 1036 print_and_free_err(&err);1037 return sqlite3_mprintf("%d checkpoints", nCkpt);1038}1039 1040static void walthread1(int nMs){1041 Error err = {0}; /* Error code and message */1042 Sqlite db = {0}; /* SQLite database connection */1043 Threadset threads = {0}; /* Test threads */1044 int i; /* Iterator variable */1045 1046 opendb(&err, &db, "test.db", 1);1047 sql_script(&err, &db,1048 "PRAGMA journal_mode = WAL;"1049 "CREATE TABLE t1(x PRIMARY KEY);"1050 "INSERT INTO t1 VALUES(randomblob(100));"1051 "INSERT INTO t1 VALUES(randomblob(100));"1052 "INSERT INTO t1 SELECT md5sum(x) FROM t1;"1053 );1054 closedb(&err, &db);1055 1056 setstoptime(&err, nMs);1057 for(i=0; i<WALTHREAD1_NTHREAD; i++){1058 launch_thread(&err, &threads, walthread1_thread, 0);1059 }1060 launch_thread(&err, &threads, walthread1_ckpt_thread, 0);1061 join_all_threads(&err, &threads);1062 1063 print_and_free_err(&err);1064}1065 1066static char *walthread2_thread(int iTid, void *pArg){1067 Error err = {0}; /* Error code and message */1068 Sqlite db = {0}; /* SQLite database connection */1069 int anTrans[2] = {0, 0}; /* Number of WAL and Rollback transactions */1070 int iArg = PTR2INT(pArg);1071 1072 const char *zJournal = "PRAGMA journal_mode = WAL";1073 if( iArg ){ zJournal = "PRAGMA journal_mode = DELETE"; }1074 1075 while( !timetostop(&err) ){1076 int journal_exists = 0;1077 int wal_exists = 0;1078 1079 opendb(&err, &db, "test.db", 0);1080 1081 sql_script(&err, &db, zJournal);1082 clear_error(&err, SQLITE_BUSY);1083 sql_script(&err, &db, "BEGIN");1084 sql_script(&err, &db, "INSERT INTO t1 VALUES(NULL, randomblob(100))");1085 1086 journal_exists = (filesize(&err, "test.db-journal") >= 0);1087 wal_exists = (filesize(&err, "test.db-wal") >= 0);1088 if( (journal_exists+wal_exists)!=1 ){1089 test_error(&err, "File system looks incorrect (%d, %d)", 1090 journal_exists, wal_exists1091 );1092 }1093 anTrans[journal_exists]++;1094 1095 sql_script(&err, &db, "COMMIT");1096 integrity_check(&err, &db);1097 closedb(&err, &db);1098 }1099 1100 print_and_free_err(&err);1101 return sqlite3_mprintf("W %d R %d", anTrans[0], anTrans[1]);1102}1103 1104static void walthread2(int nMs){1105 Error err = {0};1106 Sqlite db = {0};1107 Threadset threads = {0};1108 1109 opendb(&err, &db, "test.db", 1);1110 sql_script(&err, &db, "CREATE TABLE t1(x INTEGER PRIMARY KEY, y UNIQUE)");1111 closedb(&err, &db);1112 1113 setstoptime(&err, nMs);1114 launch_thread(&err, &threads, walthread2_thread, 0);1115 launch_thread(&err, &threads, walthread2_thread, 0);1116 launch_thread(&err, &threads, walthread2_thread, (void*)1);1117 launch_thread(&err, &threads, walthread2_thread, (void*)1);1118 join_all_threads(&err, &threads);1119 1120 print_and_free_err(&err);1121}1122 1123static char *walthread3_thread(int iTid, void *pArg){1124 Error err = {0}; /* Error code and message */1125 Sqlite db = {0}; /* SQLite database connection */1126 i64 iNextWrite; /* Next value this thread will write */1127 int iArg = PTR2INT(pArg);1128 1129 opendb(&err, &db, "test.db", 0);1130 sql_script(&err, &db, "PRAGMA wal_autocheckpoint = 10");1131 1132 iNextWrite = iArg+1;1133 while( 1 ){1134 i64 sum1;1135 i64 sum2;1136 int stop = 0; /* True to stop executing (test timed out) */1137 1138 while( 0==(stop = timetostop(&err)) ){1139 i64 iMax = execsql_i64(&err, &db, "SELECT max(cnt) FROM t1");1140 if( iMax+1==iNextWrite ) break;1141 }1142 if( stop ) break;1143 1144 sum1 = execsql_i64(&err, &db, "SELECT sum(cnt) FROM t1");1145 sum2 = execsql_i64(&err, &db, "SELECT sum(sum1) FROM t1");1146 execsql_i64(&err, &db, 1147 "INSERT INTO t1 VALUES(:iNextWrite, :iSum1, :iSum2)",1148 &iNextWrite, &sum1, &sum21149 );1150 integrity_check(&err, &db);1151 1152 iNextWrite += WALTHREAD3_NTHREAD;1153 }1154 1155 closedb(&err, &db);1156 print_and_free_err(&err);1157 return 0;1158}1159 1160static void walthread3(int nMs){1161 Error err = {0};1162 Sqlite db = {0};1163 Threadset threads = {0};1164 int i;1165 1166 opendb(&err, &db, "test.db", 1);1167 sql_script(&err, &db, 1168 "PRAGMA journal_mode = WAL;"1169 "CREATE TABLE t1(cnt PRIMARY KEY, sum1, sum2);"1170 "CREATE INDEX i1 ON t1(sum1);"1171 "CREATE INDEX i2 ON t1(sum2);"1172 "INSERT INTO t1 VALUES(0, 0, 0);"1173 );1174 closedb(&err, &db);1175 1176 setstoptime(&err, nMs);1177 for(i=0; i<WALTHREAD3_NTHREAD; i++){1178 launch_thread(&err, &threads, walthread3_thread, INT2PTR(i));1179 }1180 join_all_threads(&err, &threads);1181 1182 print_and_free_err(&err);1183}1184 1185static char *walthread4_reader_thread(int iTid, void *pArg){1186 Error err = {0}; /* Error code and message */1187 Sqlite db = {0}; /* SQLite database connection */1188 1189 opendb(&err, &db, "test.db", 0);1190 while( !timetostop(&err) ){1191 integrity_check(&err, &db);1192 }1193 closedb(&err, &db);1194 1195 print_and_free_err(&err);1196 return 0;1197}1198 1199static char *walthread4_writer_thread(int iTid, void *pArg){1200 Error err = {0}; /* Error code and message */