blob: fe5eb2d9d57344bde60c301cd3a89d28aea009d6 [file] [log] [blame]
drh3b74d032015-05-25 18:48:19 +00001/*
2** 2015-05-25
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** This is a utility program designed to aid running regressions tests
14** on SQLite library using data from an external fuzzer, such as American
15** Fuzzy Lop (AFL) (http://lcamtuf.coredump.cx/afl/).
16**
17** This program reads content from an SQLite database file with the following
18** schema:
19**
20** CREATE TABLE db(
21** dbid INTEGER PRIMARY KEY, -- database id
22** dbcontent BLOB -- database disk file image
23** );
24** CREATE TABLE xsql(
25** sqlid INTEGER PRIMARY KEY, -- SQL script id
26** sqltext TEXT -- Text of SQL statements to run
27** );
28**
29** For each database file in the DB table, the SQL text in the XSQL table
30** is run against that database. This program is looking for crashes,
31** assertion faults, and/or memory leaks. No attempt is made to verify
32** the output. The assumption is that either all of the database files
33** or all of the SQL statements are malformed inputs, generated by a fuzzer,
34** that need to be checked to make sure they do not present a security risk.
35**
36** This program also includes some command-line options to help with
37** creation and maintenance of the source content database.
38*/
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <stdarg.h>
43#include <ctype.h>
44#include "sqlite3.h"
45
46/*
47** Files in the virtual file system.
48*/
49typedef struct VFile VFile;
50struct VFile {
51 char *zFilename; /* Filename. NULL for delete-on-close. From malloc() */
52 int sz; /* Size of the file in bytes */
53 int nRef; /* Number of references to this file */
54 unsigned char *a; /* Content of the file. From malloc() */
55};
56typedef struct VHandle VHandle;
57struct VHandle {
58 sqlite3_file base; /* Base class. Must be first */
59 VFile *pVFile; /* The underlying file */
60};
61
62/*
63** The value of a database file template, or of an SQL script
64*/
65typedef struct Blob Blob;
66struct Blob {
67 Blob *pNext; /* Next in a list */
68 int id; /* Id of this Blob */
drhe5c5f2c2015-05-26 00:28:08 +000069 int seq; /* Sequence number */
drh3b74d032015-05-25 18:48:19 +000070 int sz; /* Size of this Blob in bytes */
71 unsigned char a[1]; /* Blob content. Extra space allocated as needed. */
72};
73
74/*
75** Maximum number of files in the in-memory virtual filesystem.
76*/
77#define MX_FILE 10
78
79/*
80** Maximum allowed file size
81*/
82#define MX_FILE_SZ 10000000
83
84/*
85** All global variables are gathered into the "g" singleton.
86*/
87static struct GlobalVars {
88 const char *zArgv0; /* Name of program */
89 VFile aFile[MX_FILE]; /* The virtual filesystem */
90 int nDb; /* Number of template databases */
91 Blob *pFirstDb; /* Content of first template database */
92 int nSql; /* Number of SQL scripts */
93 Blob *pFirstSql; /* First SQL script */
94 char zTestName[100]; /* Name of current test */
95} g;
96
97/*
98** Print an error message and quit.
99*/
100static void fatalError(const char *zFormat, ...){
101 va_list ap;
102 if( g.zTestName[0] ){
103 fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
104 }else{
105 fprintf(stderr, "%s: ", g.zArgv0);
106 }
107 va_start(ap, zFormat);
108 vfprintf(stderr, zFormat, ap);
109 va_end(ap);
110 fprintf(stderr, "\n");
111 exit(1);
112}
113
114/*
115** Reallocate memory. Show and error and quit if unable.
116*/
117static void *safe_realloc(void *pOld, int szNew){
118 void *pNew = realloc(pOld, szNew);
119 if( pNew==0 ) fatalError("unable to realloc for %d bytes", szNew);
120 return pNew;
121}
122
123/*
124** Initialize the virtual file system.
125*/
126static void formatVfs(void){
127 int i;
128 for(i=0; i<MX_FILE; i++){
129 g.aFile[i].sz = -1;
130 g.aFile[i].zFilename = 0;
131 g.aFile[i].a = 0;
132 g.aFile[i].nRef = 0;
133 }
134}
135
136
137/*
138** Erase all information in the virtual file system.
139*/
140static void reformatVfs(void){
141 int i;
142 for(i=0; i<MX_FILE; i++){
143 if( g.aFile[i].sz<0 ) continue;
144 if( g.aFile[i].zFilename ){
145 free(g.aFile[i].zFilename);
146 g.aFile[i].zFilename = 0;
147 }
148 if( g.aFile[i].nRef>0 ){
149 fatalError("file %d still open. nRef=%d", i, g.aFile[i].nRef);
150 }
151 g.aFile[i].sz = -1;
152 free(g.aFile[i].a);
153 g.aFile[i].a = 0;
154 g.aFile[i].nRef = 0;
155 }
156}
157
158/*
159** Find a VFile by name
160*/
161static VFile *findVFile(const char *zName){
162 int i;
drha9542b12015-05-25 19:35:42 +0000163 if( zName==0 ) return 0;
drh3b74d032015-05-25 18:48:19 +0000164 for(i=0; i<MX_FILE; i++){
165 if( g.aFile[i].zFilename==0 ) continue;
166 if( strcmp(g.aFile[i].zFilename, zName)==0 ) return &g.aFile[i];
167 }
168 return 0;
169}
170
171/*
172** Find a VFile by name. Create it if it does not already exist and
173** initialize it to the size and content given.
174**
175** Return NULL only if the filesystem is full.
176*/
177static VFile *createVFile(const char *zName, int sz, unsigned char *pData){
178 VFile *pNew = findVFile(zName);
179 int i;
180 if( pNew ) return pNew;
181 for(i=0; i<MX_FILE && g.aFile[i].sz>=0; i++){}
182 if( i>=MX_FILE ) return 0;
183 pNew = &g.aFile[i];
drha9542b12015-05-25 19:35:42 +0000184 if( zName ){
185 pNew->zFilename = safe_realloc(0, strlen(zName)+1);
186 memcpy(pNew->zFilename, zName, strlen(zName)+1);
187 }else{
188 pNew->zFilename = 0;
189 }
drh3b74d032015-05-25 18:48:19 +0000190 pNew->nRef = 0;
191 pNew->sz = sz;
192 pNew->a = safe_realloc(0, sz);
193 if( sz>0 ) memcpy(pNew->a, pData, sz);
194 return pNew;
195}
196
197
198/*
199** Implementation of the "readfile(X)" SQL function. The entire content
200** of the file named X is read and returned as a BLOB. NULL is returned
201** if the file does not exist or is unreadable.
202*/
203static void readfileFunc(
204 sqlite3_context *context,
205 int argc,
206 sqlite3_value **argv
207){
208 const char *zName;
209 FILE *in;
210 long nIn;
211 void *pBuf;
212
213 zName = (const char*)sqlite3_value_text(argv[0]);
214 if( zName==0 ) return;
215 in = fopen(zName, "rb");
216 if( in==0 ) return;
217 fseek(in, 0, SEEK_END);
218 nIn = ftell(in);
219 rewind(in);
220 pBuf = sqlite3_malloc64( nIn );
221 if( pBuf && 1==fread(pBuf, nIn, 1, in) ){
222 sqlite3_result_blob(context, pBuf, nIn, sqlite3_free);
223 }else{
224 sqlite3_free(pBuf);
225 }
226 fclose(in);
227}
228
229/*
drh3b74d032015-05-25 18:48:19 +0000230** Load a list of Blob objects from the database
231*/
232static void blobListLoadFromDb(
233 sqlite3 *db, /* Read from this database */
234 const char *zSql, /* Query used to extract the blobs */
drha9542b12015-05-25 19:35:42 +0000235 int onlyId, /* Only load where id is this value */
drh3b74d032015-05-25 18:48:19 +0000236 int *pN, /* OUT: Write number of blobs loaded here */
237 Blob **ppList /* OUT: Write the head of the blob list here */
238){
239 Blob head;
240 Blob *p;
241 sqlite3_stmt *pStmt;
242 int n = 0;
243 int rc;
drha9542b12015-05-25 19:35:42 +0000244 char *z2;
drh3b74d032015-05-25 18:48:19 +0000245
drha9542b12015-05-25 19:35:42 +0000246 if( onlyId>0 ){
247 z2 = sqlite3_mprintf("%s WHERE rowid=%d", zSql, onlyId);
248 }else{
249 z2 = sqlite3_mprintf("%s", zSql);
250 }
251 rc = sqlite3_prepare_v2(db, z2, -1, &pStmt, 0);
252 sqlite3_free(z2);
drh3b74d032015-05-25 18:48:19 +0000253 if( rc ) fatalError("%s", sqlite3_errmsg(db));
254 head.pNext = 0;
255 p = &head;
256 while( SQLITE_ROW==sqlite3_step(pStmt) ){
257 int sz = sqlite3_column_bytes(pStmt, 1);
258 Blob *pNew = safe_realloc(0, sizeof(*pNew)+sz );
259 pNew->id = sqlite3_column_int(pStmt, 0);
260 pNew->sz = sz;
drhe5c5f2c2015-05-26 00:28:08 +0000261 pNew->seq = n++;
drh3b74d032015-05-25 18:48:19 +0000262 pNew->pNext = 0;
263 memcpy(pNew->a, sqlite3_column_blob(pStmt,1), sz);
264 pNew->a[sz] = 0;
265 p->pNext = pNew;
266 p = pNew;
drh3b74d032015-05-25 18:48:19 +0000267 }
268 sqlite3_finalize(pStmt);
269 *pN = n;
270 *ppList = head.pNext;
271}
272
273/*
274** Free a list of Blob objects
275*/
276static void blobListFree(Blob *p){
277 Blob *pNext;
278 while( p ){
279 pNext = p->pNext;
280 free(p);
281 p = pNext;
282 }
283}
284
285
286/* Return the current wall-clock time */
287static sqlite3_int64 timeOfDay(void){
288 static sqlite3_vfs *clockVfs = 0;
289 sqlite3_int64 t;
290 if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
291 if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
292 clockVfs->xCurrentTimeInt64(clockVfs, &t);
293 }else{
294 double r;
295 clockVfs->xCurrentTime(clockVfs, &r);
296 t = (sqlite3_int64)(r*86400000.0);
297 }
298 return t;
299}
300
301/* Methods for the VHandle object
302*/
303static int inmemClose(sqlite3_file *pFile){
304 VHandle *p = (VHandle*)pFile;
305 VFile *pVFile = p->pVFile;
306 pVFile->nRef--;
307 if( pVFile->nRef==0 && pVFile->zFilename==0 ){
308 pVFile->sz = -1;
309 free(pVFile->a);
310 pVFile->a = 0;
311 }
312 return SQLITE_OK;
313}
314static int inmemRead(
315 sqlite3_file *pFile, /* Read from this open file */
316 void *pData, /* Store content in this buffer */
317 int iAmt, /* Bytes of content */
318 sqlite3_int64 iOfst /* Start reading here */
319){
320 VHandle *pHandle = (VHandle*)pFile;
321 VFile *pVFile = pHandle->pVFile;
322 if( iOfst<0 || iOfst>=pVFile->sz ){
323 memset(pData, 0, iAmt);
324 return SQLITE_IOERR_SHORT_READ;
325 }
326 if( iOfst+iAmt>pVFile->sz ){
327 memset(pData, 0, iAmt);
drh1573dc32015-05-25 22:29:26 +0000328 iAmt = (int)(pVFile->sz - iOfst);
drh3b74d032015-05-25 18:48:19 +0000329 memcpy(pData, pVFile->a, iAmt);
330 return SQLITE_IOERR_SHORT_READ;
331 }
drhaca7ea12015-05-25 23:14:37 +0000332 memcpy(pData, pVFile->a + iOfst, iAmt);
drh3b74d032015-05-25 18:48:19 +0000333 return SQLITE_OK;
334}
335static int inmemWrite(
336 sqlite3_file *pFile, /* Write to this file */
337 const void *pData, /* Content to write */
338 int iAmt, /* bytes to write */
339 sqlite3_int64 iOfst /* Start writing here */
340){
341 VHandle *pHandle = (VHandle*)pFile;
342 VFile *pVFile = pHandle->pVFile;
343 if( iOfst+iAmt > pVFile->sz ){
drha9542b12015-05-25 19:35:42 +0000344 if( iOfst+iAmt >= MX_FILE_SZ ){
345 return SQLITE_FULL;
346 }
drh1573dc32015-05-25 22:29:26 +0000347 pVFile->a = safe_realloc(pVFile->a, (int)(iOfst+iAmt));
drh908aced2015-05-26 16:12:45 +0000348 if( iOfst > pVFile->sz ){
349 memset(pVFile->a + pVFile->sz, 0, (int)(iOfst - pVFile->sz));
350 }
drh1573dc32015-05-25 22:29:26 +0000351 pVFile->sz = (int)(iOfst + iAmt);
drh3b74d032015-05-25 18:48:19 +0000352 }
353 memcpy(pVFile->a + iOfst, pData, iAmt);
354 return SQLITE_OK;
355}
356static int inmemTruncate(sqlite3_file *pFile, sqlite3_int64 iSize){
357 VHandle *pHandle = (VHandle*)pFile;
358 VFile *pVFile = pHandle->pVFile;
drh1573dc32015-05-25 22:29:26 +0000359 if( pVFile->sz>iSize && iSize>=0 ) pVFile->sz = (int)iSize;
drh3b74d032015-05-25 18:48:19 +0000360 return SQLITE_OK;
361}
362static int inmemSync(sqlite3_file *pFile, int flags){
363 return SQLITE_OK;
364}
365static int inmemFileSize(sqlite3_file *pFile, sqlite3_int64 *pSize){
366 *pSize = ((VHandle*)pFile)->pVFile->sz;
367 return SQLITE_OK;
368}
369static int inmemLock(sqlite3_file *pFile, int type){
370 return SQLITE_OK;
371}
372static int inmemUnlock(sqlite3_file *pFile, int type){
373 return SQLITE_OK;
374}
375static int inmemCheckReservedLock(sqlite3_file *pFile, int *pOut){
376 *pOut = 0;
377 return SQLITE_OK;
378}
379static int inmemFileControl(sqlite3_file *pFile, int op, void *pArg){
380 return SQLITE_NOTFOUND;
381}
382static int inmemSectorSize(sqlite3_file *pFile){
383 return 512;
384}
385static int inmemDeviceCharacteristics(sqlite3_file *pFile){
386 return
387 SQLITE_IOCAP_SAFE_APPEND |
388 SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
389 SQLITE_IOCAP_POWERSAFE_OVERWRITE;
390}
391
392
393/* Method table for VHandle
394*/
395static sqlite3_io_methods VHandleMethods = {
396 /* iVersion */ 1,
397 /* xClose */ inmemClose,
398 /* xRead */ inmemRead,
399 /* xWrite */ inmemWrite,
400 /* xTruncate */ inmemTruncate,
401 /* xSync */ inmemSync,
402 /* xFileSize */ inmemFileSize,
403 /* xLock */ inmemLock,
404 /* xUnlock */ inmemUnlock,
405 /* xCheck... */ inmemCheckReservedLock,
406 /* xFileCtrl */ inmemFileControl,
407 /* xSectorSz */ inmemSectorSize,
408 /* xDevchar */ inmemDeviceCharacteristics,
409 /* xShmMap */ 0,
410 /* xShmLock */ 0,
411 /* xShmBarrier */ 0,
412 /* xShmUnmap */ 0,
413 /* xFetch */ 0,
414 /* xUnfetch */ 0
415};
416
417/*
418** Open a new file in the inmem VFS. All files are anonymous and are
419** delete-on-close.
420*/
421static int inmemOpen(
422 sqlite3_vfs *pVfs,
423 const char *zFilename,
424 sqlite3_file *pFile,
425 int openFlags,
426 int *pOutFlags
427){
428 VFile *pVFile = createVFile(zFilename, 0, (unsigned char*)"");
429 VHandle *pHandle = (VHandle*)pFile;
drha9542b12015-05-25 19:35:42 +0000430 if( pVFile==0 ){
431 return SQLITE_FULL;
432 }
drh3b74d032015-05-25 18:48:19 +0000433 pHandle->pVFile = pVFile;
434 pVFile->nRef++;
435 pFile->pMethods = &VHandleMethods;
436 if( pOutFlags ) *pOutFlags = openFlags;
437 return SQLITE_OK;
438}
439
440/*
441** Delete a file by name
442*/
443static int inmemDelete(
444 sqlite3_vfs *pVfs,
445 const char *zFilename,
446 int syncdir
447){
448 VFile *pVFile = findVFile(zFilename);
449 if( pVFile==0 ) return SQLITE_OK;
450 if( pVFile->nRef==0 ){
451 free(pVFile->zFilename);
452 pVFile->zFilename = 0;
453 pVFile->sz = -1;
454 free(pVFile->a);
455 pVFile->a = 0;
456 return SQLITE_OK;
457 }
458 return SQLITE_IOERR_DELETE;
459}
460
461/* Check for the existance of a file
462*/
463static int inmemAccess(
464 sqlite3_vfs *pVfs,
465 const char *zFilename,
466 int flags,
467 int *pResOut
468){
469 VFile *pVFile = findVFile(zFilename);
470 *pResOut = pVFile!=0;
471 return SQLITE_OK;
472}
473
474/* Get the canonical pathname for a file
475*/
476static int inmemFullPathname(
477 sqlite3_vfs *pVfs,
478 const char *zFilename,
479 int nOut,
480 char *zOut
481){
482 sqlite3_snprintf(nOut, zOut, "%s", zFilename);
483 return SQLITE_OK;
484}
485
486/* GetLastError() is never used */
487static int inmemGetLastError(sqlite3_vfs *pVfs, int n, char *z){
488 return SQLITE_OK;
489}
490
491/*
492** Register the VFS that reads from the g.aFile[] set of files.
493*/
494static void inmemVfsRegister(void){
495 static sqlite3_vfs inmemVfs;
496 sqlite3_vfs *pDefault = sqlite3_vfs_find(0);
497 inmemVfs.iVersion = 1;
498 inmemVfs.szOsFile = sizeof(VHandle);
499 inmemVfs.mxPathname = 200;
500 inmemVfs.zName = "inmem";
501 inmemVfs.xOpen = inmemOpen;
502 inmemVfs.xDelete = inmemDelete;
503 inmemVfs.xAccess = inmemAccess;
504 inmemVfs.xFullPathname = inmemFullPathname;
505 inmemVfs.xRandomness = pDefault->xRandomness;
506 inmemVfs.xSleep = pDefault->xSleep;
507 inmemVfs.xCurrentTime = pDefault->xCurrentTime;
508 inmemVfs.xGetLastError = inmemGetLastError;
509 sqlite3_vfs_register(&inmemVfs, 0);
510};
511
drh3b74d032015-05-25 18:48:19 +0000512/*
drhe5c5f2c2015-05-26 00:28:08 +0000513** Allowed values for the runFlags parameter to runSql()
514*/
515#define SQL_TRACE 0x0001 /* Print each SQL statement as it is prepared */
516#define SQL_OUTPUT 0x0002 /* Show the SQL output */
517
518/*
drh3b74d032015-05-25 18:48:19 +0000519** Run multiple commands of SQL. Similar to sqlite3_exec(), but does not
520** stop if an error is encountered.
521*/
drhe5c5f2c2015-05-26 00:28:08 +0000522static void runSql(sqlite3 *db, const char *zSql, unsigned runFlags){
drh3b74d032015-05-25 18:48:19 +0000523 const char *zMore;
524 sqlite3_stmt *pStmt;
525
526 while( zSql && zSql[0] ){
527 zMore = 0;
528 pStmt = 0;
529 sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zMore);
drh4ab31472015-05-25 22:17:06 +0000530 if( zMore==zSql ) break;
drhe5c5f2c2015-05-26 00:28:08 +0000531 if( runFlags & SQL_TRACE ){
drh4ab31472015-05-25 22:17:06 +0000532 const char *z = zSql;
533 int n;
534 while( z<zMore && isspace(z[0]) ) z++;
535 n = (int)(zMore - z);
536 while( n>0 && isspace(z[n-1]) ) n--;
537 if( n==0 ) break;
538 if( pStmt==0 ){
539 printf("TRACE: %.*s (error: %s)\n", n, z, sqlite3_errmsg(db));
540 }else{
541 printf("TRACE: %.*s\n", n, z);
542 }
543 }
drh3b74d032015-05-25 18:48:19 +0000544 zSql = zMore;
545 if( pStmt ){
drhe5c5f2c2015-05-26 00:28:08 +0000546 if( (runFlags & SQL_OUTPUT)==0 ){
547 while( SQLITE_ROW==sqlite3_step(pStmt) ){}
548 }else{
549 int nCol = -1;
550 while( SQLITE_ROW==sqlite3_step(pStmt) ){
551 int i;
552 if( nCol<0 ){
553 nCol = sqlite3_column_count(pStmt);
554 }else if( nCol>0 ){
555 printf("--------------------------------------------\n");
556 }
557 for(i=0; i<nCol; i++){
558 int eType = sqlite3_column_type(pStmt,i);
559 printf("%s = ", sqlite3_column_name(pStmt,i));
560 switch( eType ){
561 case SQLITE_NULL: {
562 printf("NULL\n");
563 break;
564 }
565 case SQLITE_INTEGER: {
566 printf("INT %s\n", sqlite3_column_text(pStmt,i));
567 break;
568 }
569 case SQLITE_FLOAT: {
570 printf("FLOAT %s\n", sqlite3_column_text(pStmt,i));
571 break;
572 }
573 case SQLITE_TEXT: {
574 printf("TEXT [%s]\n", sqlite3_column_text(pStmt,i));
575 break;
576 }
577 case SQLITE_BLOB: {
578 printf("BLOB (%d bytes)\n", sqlite3_column_bytes(pStmt,i));
579 break;
580 }
581 }
582 }
583 }
584 }
drh3b74d032015-05-25 18:48:19 +0000585 sqlite3_finalize(pStmt);
drh3b74d032015-05-25 18:48:19 +0000586 }
587 }
588}
589
drha9542b12015-05-25 19:35:42 +0000590/*
591** Print sketchy documentation for this utility program
592*/
593static void showHelp(void){
594 printf("Usage: %s [options] SOURCE-DB ?ARGS...?\n", g.zArgv0);
595 printf(
596"Read databases and SQL scripts from SOURCE-DB and execute each script against\n"
597"each database, checking for crashes and memory leaks.\n"
598"Options:\n"
599" --dbid N Use only the database where dbid=N\n"
600" --help Show this help text\n"
601" -q Reduced output\n"
602" --quiet Reduced output\n"
603" --load-sql ARGS... Load SQL scripts fro files into SOURCE-DB\n"
604" --load-db ARGS... Load template databases from files into SOURCE_DB\n"
drhd9972ef2015-05-26 17:57:56 +0000605" -m TEXT Add a description to the database\n"
drh15b31282015-05-25 21:59:05 +0000606" --native-vfs Use the native VFS for initially empty database files\n"
drhe5c5f2c2015-05-26 00:28:08 +0000607" --result-trace Show the results of each SQL command\n"
drha9542b12015-05-25 19:35:42 +0000608" --sqlid N Use only SQL where sqlid=N\n"
609" -v Increased output\n"
610" --verbose Increased output\n"
611 );
612}
613
drh3b74d032015-05-25 18:48:19 +0000614int main(int argc, char **argv){
615 sqlite3_int64 iBegin; /* Start time of this program */
drh3b74d032015-05-25 18:48:19 +0000616 int quietFlag = 0; /* True if --quiet or -q */
617 int verboseFlag = 0; /* True if --verbose or -v */
618 char *zInsSql = 0; /* SQL statement for --load-db or --load-sql */
619 int iFirstInsArg = 0; /* First argv[] to use for --load-db or --load-sql */
620 sqlite3 *db = 0; /* The open database connection */
drhd9972ef2015-05-26 17:57:56 +0000621 sqlite3_stmt *pStmt; /* A prepared statement */
drh3b74d032015-05-25 18:48:19 +0000622 int rc; /* Result code from SQLite interface calls */
623 Blob *pSql; /* For looping over SQL scripts */
624 Blob *pDb; /* For looping over template databases */
625 int i; /* Loop index for the argv[] loop */
drha9542b12015-05-25 19:35:42 +0000626 int onlySqlid = -1; /* --sqlid */
627 int onlyDbid = -1; /* --dbid */
drh15b31282015-05-25 21:59:05 +0000628 int nativeFlag = 0; /* --native-vfs */
drhe5c5f2c2015-05-26 00:28:08 +0000629 int runFlags = 0; /* Flags sent to runSql() */
drhd9972ef2015-05-26 17:57:56 +0000630 char *zMsg = 0; /* Add this message */
631 int nSrcDb = 0; /* Number of source databases */
632 char **azSrcDb = 0; /* Array of source database names */
633 int iSrcDb; /* Loop over all source databases */
634 int nTest = 0; /* Total number of tests performed */
635 char *zDbName = ""; /* Appreviated name of a source database */
drh4d6fda72015-05-26 18:58:32 +0000636 const char *zFailCode = 0; /* Value of the TEST_FAILURE environment variable */
drh3b74d032015-05-25 18:48:19 +0000637
638 iBegin = timeOfDay();
639 g.zArgv0 = argv[0];
drh4d6fda72015-05-26 18:58:32 +0000640 zFailCode = getenv("TEST_FAILURE");
drh3b74d032015-05-25 18:48:19 +0000641 for(i=1; i<argc; i++){
642 const char *z = argv[i];
643 if( z[0]=='-' ){
644 z++;
645 if( z[0]=='-' ) z++;
drha9542b12015-05-25 19:35:42 +0000646 if( strcmp(z,"dbid")==0 ){
647 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
648 onlyDbid = atoi(argv[++i]);
649 }else
drh3b74d032015-05-25 18:48:19 +0000650 if( strcmp(z,"help")==0 ){
651 showHelp();
652 return 0;
653 }else
654 if( strcmp(z,"load-sql")==0 ){
drhe5c5f2c2015-05-26 00:28:08 +0000655 zInsSql = "INSERT INTO xsql(sqltext) VALUES(CAST(readfile(?1) AS text))";
drh3b74d032015-05-25 18:48:19 +0000656 iFirstInsArg = i+1;
657 break;
658 }else
659 if( strcmp(z,"load-db")==0 ){
660 zInsSql = "INSERT INTO db(dbcontent) VALUES(readfile(?1))";
661 iFirstInsArg = i+1;
662 break;
663 }else
drhd9972ef2015-05-26 17:57:56 +0000664 if( strcmp(z,"m")==0 ){
665 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
666 zMsg = argv[++i];
667 }else
drh15b31282015-05-25 21:59:05 +0000668 if( strcmp(z,"native-vfs")==0 ){
669 nativeFlag = 1;
670 }else
drh3b74d032015-05-25 18:48:19 +0000671 if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
672 quietFlag = 1;
673 verboseFlag = 0;
674 }else
drhe5c5f2c2015-05-26 00:28:08 +0000675 if( strcmp(z,"result-trace")==0 ){
676 runFlags |= SQL_OUTPUT;
677 }else
drha9542b12015-05-25 19:35:42 +0000678 if( strcmp(z,"sqlid")==0 ){
679 if( i>=argc-1 ) fatalError("missing arguments on %s", argv[i]);
680 onlySqlid = atoi(argv[++i]);
681 }else
drh3b74d032015-05-25 18:48:19 +0000682 if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
683 quietFlag = 0;
684 verboseFlag = 1;
drhe5c5f2c2015-05-26 00:28:08 +0000685 runFlags |= SQL_TRACE;
drh3b74d032015-05-25 18:48:19 +0000686 }else
687 {
688 fatalError("unknown option: %s", argv[i]);
689 }
690 }else{
drhd9972ef2015-05-26 17:57:56 +0000691 nSrcDb++;
692 azSrcDb = safe_realloc(azSrcDb, nSrcDb*sizeof(azSrcDb[0]));
693 azSrcDb[nSrcDb-1] = argv[i];
drh3b74d032015-05-25 18:48:19 +0000694 }
695 }
drhd9972ef2015-05-26 17:57:56 +0000696 if( nSrcDb==0 ) fatalError("no source database specified");
697 if( nSrcDb>1 ){
698 if( zMsg ){
699 fatalError("cannot change the description of more than one database");
drh3b74d032015-05-25 18:48:19 +0000700 }
drhd9972ef2015-05-26 17:57:56 +0000701 if( zInsSql ){
702 fatalError("cannot import into more than one database");
703 }
drh3b74d032015-05-25 18:48:19 +0000704 }
705
drhd9972ef2015-05-26 17:57:56 +0000706 /* Process each source database separately */
707 for(iSrcDb=0; iSrcDb<nSrcDb; iSrcDb++){
708 rc = sqlite3_open(azSrcDb[iSrcDb], &db);
709 if( rc ){
710 fatalError("cannot open source database %s - %s",
711 azSrcDb[iSrcDb], sqlite3_errmsg(db));
712 }
713 rc = sqlite3_exec(db,
714 "CREATE TABLE IF NOT EXISTS db(\n"
715 " dbid INTEGER PRIMARY KEY, -- database id\n"
716 " dbcontent BLOB -- database disk file image\n"
717 ");\n"
718 "CREATE TABLE IF NOT EXISTS xsql(\n"
719 " sqlid INTEGER PRIMARY KEY, -- SQL script id\n"
720 " sqltext TEXT -- Text of SQL statements to run\n"
721 ");"
722 "CREATE TABLE IF NOT EXISTS readme(\n"
723 " msg TEXT -- Human-readable description of this file\n"
724 ");", 0, 0, 0);
725 if( rc ) fatalError("cannot create schema: %s", sqlite3_errmsg(db));
726 if( zMsg ){
727 char *zSql;
728 zSql = sqlite3_mprintf(
729 "DELETE FROM readme; INSERT INTO readme(msg) VALUES(%Q)", zMsg);
730 rc = sqlite3_exec(db, zSql, 0, 0, 0);
731 sqlite3_free(zSql);
732 if( rc ) fatalError("cannot change description: %s", sqlite3_errmsg(db));
733 }
734 if( zInsSql ){
735 sqlite3_create_function(db, "readfile", 1, SQLITE_UTF8, 0,
736 readfileFunc, 0, 0);
737 rc = sqlite3_prepare_v2(db, zInsSql, -1, &pStmt, 0);
738 if( rc ) fatalError("cannot prepare statement [%s]: %s",
739 zInsSql, sqlite3_errmsg(db));
740 rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
741 if( rc ) fatalError("cannot start a transaction");
742 for(i=iFirstInsArg; i<argc; i++){
743 sqlite3_bind_text(pStmt, 1, argv[i], -1, SQLITE_STATIC);
744 sqlite3_step(pStmt);
745 rc = sqlite3_reset(pStmt);
746 if( rc ) fatalError("insert failed for %s", argv[i]);
drh3b74d032015-05-25 18:48:19 +0000747 }
drhd9972ef2015-05-26 17:57:56 +0000748 sqlite3_finalize(pStmt);
749 rc = sqlite3_exec(db, "COMMIT", 0, 0, 0);
750 if( rc ) fatalError("cannot commit the transaction: %s", sqlite3_errmsg(db));
drh3b74d032015-05-25 18:48:19 +0000751 sqlite3_close(db);
drhd9972ef2015-05-26 17:57:56 +0000752 return 0;
drh3b74d032015-05-25 18:48:19 +0000753 }
drhd9972ef2015-05-26 17:57:56 +0000754
755 /* Load all SQL script content and all initial database images from the
756 ** source db
757 */
758 blobListLoadFromDb(db, "SELECT sqlid, sqltext FROM xsql", onlySqlid,
759 &g.nSql, &g.pFirstSql);
760 if( g.nSql==0 ) fatalError("need at least one SQL script");
761 blobListLoadFromDb(db, "SELECT dbid, dbcontent FROM db", onlyDbid,
762 &g.nDb, &g.pFirstDb);
763 if( g.nDb==0 ){
764 g.pFirstDb = safe_realloc(0, sizeof(Blob));
765 memset(g.pFirstDb, 0, sizeof(Blob));
766 g.pFirstDb->id = 1;
767 g.pFirstDb->seq = 0;
768 g.nDb = 1;
769 }
770
771 /* Print the description, if there is one */
772 if( !quietFlag ){
773 int i;
774 zDbName = azSrcDb[iSrcDb];
775 i = strlen(zDbName) - 1;
776 while( i>0 && zDbName[i-1]!='/' && zDbName[i-1]!='\\' ){ i--; }
777 zDbName += i;
778 sqlite3_prepare_v2(db, "SELECT msg FROM readme", -1, &pStmt, 0);
779 if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
780 printf("%s: %s\n", zDbName, sqlite3_column_text(pStmt,0));
781 }
782 sqlite3_finalize(pStmt);
783 }
784
785 /* Close the source database. Verify that no SQLite memory allocations are
786 ** outstanding.
787 */
788 sqlite3_close(db);
789 if( sqlite3_memory_used()>0 ){
790 fatalError("SQLite has memory in use before the start of testing");
791 }
792
793 /* Register the in-memory virtual filesystem
794 */
795 formatVfs();
796 inmemVfsRegister();
797
798 /* Run a test using each SQL script against each database.
799 */
800 if( !verboseFlag && !quietFlag ) printf("%s:", zDbName);
801 for(pSql=g.pFirstSql; pSql; pSql=pSql->pNext){
802 for(pDb=g.pFirstDb; pDb; pDb=pDb->pNext){
803 int openFlags;
804 const char *zVfs = "inmem";
805 sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "sqlid=%d,dbid=%d",
806 pSql->id, pDb->id);
807 if( verboseFlag ){
808 printf("%s\n", g.zTestName);
809 fflush(stdout);
810 }else if( !quietFlag ){
811 static int prevAmt = -1;
812 int idx = pSql->seq*g.nDb + pDb->id - 1;
813 int amt = idx*10/(g.nDb*g.nSql);
814 if( amt!=prevAmt ){
815 printf(" %d%%", amt*10);
816 fflush(stdout);
817 prevAmt = amt;
818 }
819 }
820 createVFile("main.db", pDb->sz, pDb->a);
821 openFlags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE;
822 if( nativeFlag && pDb->sz==0 ){
823 openFlags |= SQLITE_OPEN_MEMORY;
824 zVfs = 0;
825 }
826 rc = sqlite3_open_v2("main.db", &db, openFlags, zVfs);
827 if( rc ) fatalError("cannot open inmem database");
828 runSql(db, (char*)pSql->a, runFlags);
829 sqlite3_close(db);
830 if( sqlite3_memory_used()>0 ) fatalError("memory leak");
831 reformatVfs();
832 nTest++;
833 g.zTestName[0] = 0;
drh4d6fda72015-05-26 18:58:32 +0000834
835 /* Simulate an error if the TEST_FAILURE environment variable is "5".
836 ** This is used to verify that automated test script really do spot
837 ** errors that occur in this test program.
838 */
839 if( zFailCode ){
840 if( zFailCode[0]=='5' && zFailCode[1]==0 ){
841 fatalError("simulated failure");
842 }else if( zFailCode[0]!=0 ){
843 /* If TEST_FAILURE is something other than 5, just exit the test
844 ** early */
845 printf("\nExit early due to TEST_FAILURE being set\n");
846 iSrcDb = nSrcDb-1;
847 goto sourcedb_cleanup;
848 }
849 }
drhd9972ef2015-05-26 17:57:56 +0000850 }
851 }
852 if( !quietFlag && !verboseFlag ){
853 printf(" 100%% - %d tests\n", g.nDb*g.nSql);
854 }
855
856 /* Clean up at the end of processing a single source database
857 */
drh4d6fda72015-05-26 18:58:32 +0000858 sourcedb_cleanup:
drhd9972ef2015-05-26 17:57:56 +0000859 blobListFree(g.pFirstSql);
860 blobListFree(g.pFirstDb);
861 reformatVfs();
862
863 } /* End loop over all source databases */
drh3b74d032015-05-25 18:48:19 +0000864
865 if( !quietFlag ){
866 sqlite3_int64 iElapse = timeOfDay() - iBegin;
drhd9972ef2015-05-26 17:57:56 +0000867 printf("fuzzcheck: 0 errors out of %d tests in %d.%03d seconds\n"
868 "SQLite %s %s\n",
869 nTest, (int)(iElapse/1000), (int)(iElapse%1000),
drh3b74d032015-05-25 18:48:19 +0000870 sqlite3_libversion(), sqlite3_sourceid());
871 }
drh3b74d032015-05-25 18:48:19 +0000872 return 0;
873}