xref: /sqlite-3.40.0/tool/fuzzershell.c (revision 55377b47)
1 /*
2 ** 2015-04-17
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 the SQLite library
14 ** against an external fuzzer, such as American Fuzzy Lop (AFL)
15 ** (http://lcamtuf.coredump.cx/afl/).  Basically, this program reads
16 ** SQL text from standard input and passes it through to SQLite for evaluation,
17 ** just like the "sqlite3" command-line shell.  Differences from the
18 ** command-line shell:
19 **
20 **    (1)  The complex "dot-command" extensions are omitted.  This
21 **         prevents the fuzzer from discovering that it can run things
22 **         like ".shell rm -rf ~"
23 **
24 **    (2)  The database is opened with the SQLITE_OPEN_MEMORY flag so that
25 **         no disk I/O from the database is permitted.  The ATTACH command
26 **         with a filename still uses an in-memory database.
27 **
28 **    (3)  The main in-memory database can be initialized from a template
29 **         disk database so that the fuzzer starts with a database containing
30 **         content.
31 **
32 **    (4)  The eval() SQL function is added, allowing the fuzzer to do
33 **         interesting recursive operations.
34 **
35 **    (5)  An error is raised if there is a memory leak.
36 **
37 ** The input text can be divided into separate test cases using comments
38 ** of the form:
39 **
40 **       |****<...>****|
41 **
42 ** where the "..." is arbitrary text. (Except the "|" should really be "/".
43 ** "|" is used here to avoid compiler errors about nested comments.)
44 ** A separate in-memory SQLite database is created to run each test case.
45 ** This feature allows the "queue" of AFL to be captured into a single big
46 ** file using a command like this:
47 **
48 **    (for i in id:*; do echo '|****<'$i'>****|'; cat $i; done) >~/all-queue.txt
49 **
50 ** (Once again, change the "|" to "/") Then all elements of the AFL queue
51 ** can be run in a single go (for regression testing, for example) by typing:
52 **
53 **    fuzzershell -f ~/all-queue.txt
54 **
55 ** After running each chunk of SQL, the database connection is closed.  The
56 ** program aborts if the close fails or if there is any unfreed memory after
57 ** the close.
58 **
59 ** New test cases can be appended to all-queue.txt at any time.  If redundant
60 ** test cases are added, they can be eliminated by running:
61 **
62 **    fuzzershell -f ~/all-queue.txt --unique-cases ~/unique-cases.txt
63 */
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <stdarg.h>
68 #include <ctype.h>
69 #include "sqlite3.h"
70 #define ISDIGIT(X) isdigit((unsigned char)(X))
71 
72 /*
73 ** All global variables are gathered into the "g" singleton.
74 */
75 struct GlobalVars {
76   const char *zArgv0;              /* Name of program */
77   sqlite3_mem_methods sOrigMem;    /* Original memory methods */
78   sqlite3_mem_methods sOomMem;     /* Memory methods with OOM simulator */
79   int iOomCntdown;                 /* Memory fails on 1 to 0 transition */
80   int nOomFault;                   /* Increments for each OOM fault */
81   int bOomOnce;                    /* Fail just once if true */
82   int bOomEnable;                  /* True to enable OOM simulation */
83   int nOomBrkpt;                   /* Number of calls to oomFault() */
84   char zTestName[100];             /* Name of current test */
85 } g;
86 
87 /*
88 ** Maximum number of iterations for an OOM test
89 */
90 #ifndef OOM_MAX
91 # define OOM_MAX 625
92 #endif
93 
94 /*
95 ** This routine is called when a simulated OOM occurs.  It exists as a
96 ** convenient place to set a debugger breakpoint.
97 */
98 static void oomFault(void){
99   g.nOomBrkpt++; /* Prevent oomFault() from being optimized out */
100 }
101 
102 
103 /* Versions of malloc() and realloc() that simulate OOM conditions */
104 static void *oomMalloc(int nByte){
105   if( nByte>0 && g.bOomEnable && g.iOomCntdown>0 ){
106     g.iOomCntdown--;
107     if( g.iOomCntdown==0 ){
108       if( g.nOomFault==0 ) oomFault();
109       g.nOomFault++;
110       if( !g.bOomOnce ) g.iOomCntdown = 1;
111       return 0;
112     }
113   }
114   return g.sOrigMem.xMalloc(nByte);
115 }
116 static void *oomRealloc(void *pOld, int nByte){
117   if( nByte>0 && g.bOomEnable && g.iOomCntdown>0 ){
118     g.iOomCntdown--;
119     if( g.iOomCntdown==0 ){
120       if( g.nOomFault==0 ) oomFault();
121       g.nOomFault++;
122       if( !g.bOomOnce ) g.iOomCntdown = 1;
123       return 0;
124     }
125   }
126   return g.sOrigMem.xRealloc(pOld, nByte);
127 }
128 
129 /*
130 ** Print an error message and abort in such a way to indicate to the
131 ** fuzzer that this counts as a crash.
132 */
133 static void abendError(const char *zFormat, ...){
134   va_list ap;
135   if( g.zTestName[0] ){
136     fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
137   }else{
138     fprintf(stderr, "%s: ", g.zArgv0);
139   }
140   va_start(ap, zFormat);
141   vfprintf(stderr, zFormat, ap);
142   va_end(ap);
143   fprintf(stderr, "\n");
144   abort();
145 }
146 /*
147 ** Print an error message and quit, but not in a way that would look
148 ** like a crash.
149 */
150 static void fatalError(const char *zFormat, ...){
151   va_list ap;
152   if( g.zTestName[0] ){
153     fprintf(stderr, "%s (%s): ", g.zArgv0, g.zTestName);
154   }else{
155     fprintf(stderr, "%s: ", g.zArgv0);
156   }
157   va_start(ap, zFormat);
158   vfprintf(stderr, zFormat, ap);
159   va_end(ap);
160   fprintf(stderr, "\n");
161   exit(1);
162 }
163 
164 /*
165 ** Evaluate some SQL.  Abort if unable.
166 */
167 static void sqlexec(sqlite3 *db, const char *zFormat, ...){
168   va_list ap;
169   char *zSql;
170   char *zErrMsg = 0;
171   int rc;
172   va_start(ap, zFormat);
173   zSql = sqlite3_vmprintf(zFormat, ap);
174   va_end(ap);
175   rc = sqlite3_exec(db, zSql, 0, 0, &zErrMsg);
176   if( rc ) abendError("failed sql [%s]: %s", zSql, zErrMsg);
177   sqlite3_free(zSql);
178 }
179 
180 /*
181 ** This callback is invoked by sqlite3_log().
182 */
183 static void shellLog(void *pNotUsed, int iErrCode, const char *zMsg){
184   printf("LOG: (%d) %s\n", iErrCode, zMsg);
185   fflush(stdout);
186 }
187 static void shellLogNoop(void *pNotUsed, int iErrCode, const char *zMsg){
188   return;
189 }
190 
191 /*
192 ** This callback is invoked by sqlite3_exec() to return query results.
193 */
194 static int execCallback(void *NotUsed, int argc, char **argv, char **colv){
195   int i;
196   static unsigned cnt = 0;
197   printf("ROW #%u:\n", ++cnt);
198   if( argv ){
199     for(i=0; i<argc; i++){
200       printf(" %s=", colv[i]);
201       if( argv[i] ){
202         printf("[%s]\n", argv[i]);
203       }else{
204         printf("NULL\n");
205       }
206     }
207   }
208   fflush(stdout);
209   return 0;
210 }
211 static int execNoop(void *NotUsed, int argc, char **argv, char **colv){
212   return 0;
213 }
214 
215 #ifndef SQLITE_OMIT_TRACE
216 /*
217 ** This callback is invoked by sqlite3_trace() as each SQL statement
218 ** starts.
219 */
220 static void traceCallback(void *NotUsed, const char *zMsg){
221   printf("TRACE: %s\n", zMsg);
222   fflush(stdout);
223 }
224 static void traceNoop(void *NotUsed, const char *zMsg){
225   return;
226 }
227 #endif
228 
229 /***************************************************************************
230 ** eval() implementation copied from ../ext/misc/eval.c
231 */
232 /*
233 ** Structure used to accumulate the output
234 */
235 struct EvalResult {
236   char *z;               /* Accumulated output */
237   const char *zSep;      /* Separator */
238   int szSep;             /* Size of the separator string */
239   sqlite3_int64 nAlloc;  /* Number of bytes allocated for z[] */
240   sqlite3_int64 nUsed;   /* Number of bytes of z[] actually used */
241 };
242 
243 /*
244 ** Callback from sqlite_exec() for the eval() function.
245 */
246 static int callback(void *pCtx, int argc, char **argv, char **colnames){
247   struct EvalResult *p = (struct EvalResult*)pCtx;
248   int i;
249   for(i=0; i<argc; i++){
250     const char *z = argv[i] ? argv[i] : "";
251     size_t sz = strlen(z);
252     if( (sqlite3_int64)sz+p->nUsed+p->szSep+1 > p->nAlloc ){
253       char *zNew;
254       p->nAlloc = p->nAlloc*2 + sz + p->szSep + 1;
255       /* Using sqlite3_realloc64() would be better, but it is a recent
256       ** addition and will cause a segfault if loaded by an older version
257       ** of SQLite.  */
258       zNew = p->nAlloc<=0x7fffffff ? sqlite3_realloc(p->z, (int)p->nAlloc) : 0;
259       if( zNew==0 ){
260         sqlite3_free(p->z);
261         memset(p, 0, sizeof(*p));
262         return 1;
263       }
264       p->z = zNew;
265     }
266     if( p->nUsed>0 ){
267       memcpy(&p->z[p->nUsed], p->zSep, p->szSep);
268       p->nUsed += p->szSep;
269     }
270     memcpy(&p->z[p->nUsed], z, sz);
271     p->nUsed += sz;
272   }
273   return 0;
274 }
275 
276 /*
277 ** Implementation of the eval(X) and eval(X,Y) SQL functions.
278 **
279 ** Evaluate the SQL text in X.  Return the results, using string
280 ** Y as the separator.  If Y is omitted, use a single space character.
281 */
282 static void sqlEvalFunc(
283   sqlite3_context *context,
284   int argc,
285   sqlite3_value **argv
286 ){
287   const char *zSql;
288   sqlite3 *db;
289   char *zErr = 0;
290   int rc;
291   struct EvalResult x;
292 
293   memset(&x, 0, sizeof(x));
294   x.zSep = " ";
295   zSql = (const char*)sqlite3_value_text(argv[0]);
296   if( zSql==0 ) return;
297   if( argc>1 ){
298     x.zSep = (const char*)sqlite3_value_text(argv[1]);
299     if( x.zSep==0 ) return;
300   }
301   x.szSep = (int)strlen(x.zSep);
302   db = sqlite3_context_db_handle(context);
303   rc = sqlite3_exec(db, zSql, callback, &x, &zErr);
304   if( rc!=SQLITE_OK ){
305     sqlite3_result_error(context, zErr, -1);
306     sqlite3_free(zErr);
307   }else if( x.zSep==0 ){
308     sqlite3_result_error_nomem(context);
309     sqlite3_free(x.z);
310   }else{
311     sqlite3_result_text(context, x.z, (int)x.nUsed, sqlite3_free);
312   }
313 }
314 /* End of the eval() implementation
315 ******************************************************************************/
316 
317 /******************************************************************************
318 ** The generate_series(START,END,STEP) eponymous table-valued function.
319 **
320 ** This code is copy/pasted from ext/misc/series.c in the SQLite source tree.
321 */
322 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
323 ** serve as the underlying representation of a cursor that scans
324 ** over rows of the result
325 */
326 typedef struct series_cursor series_cursor;
327 struct series_cursor {
328   sqlite3_vtab_cursor base;  /* Base class - must be first */
329   int isDesc;                /* True to count down rather than up */
330   sqlite3_int64 iRowid;      /* The rowid */
331   sqlite3_int64 iValue;      /* Current value ("value") */
332   sqlite3_int64 mnValue;     /* Mimimum value ("start") */
333   sqlite3_int64 mxValue;     /* Maximum value ("stop") */
334   sqlite3_int64 iStep;       /* Increment ("step") */
335 };
336 
337 /*
338 ** The seriesConnect() method is invoked to create a new
339 ** series_vtab that describes the generate_series virtual table.
340 **
341 ** Think of this routine as the constructor for series_vtab objects.
342 **
343 ** All this routine needs to do is:
344 **
345 **    (1) Allocate the series_vtab object and initialize all fields.
346 **
347 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
348 **        result set of queries against generate_series will look like.
349 */
350 static int seriesConnect(
351   sqlite3 *db,
352   void *pAux,
353   int argc, const char *const*argv,
354   sqlite3_vtab **ppVtab,
355   char **pzErr
356 ){
357   sqlite3_vtab *pNew;
358   int rc;
359 
360 /* Column numbers */
361 #define SERIES_COLUMN_VALUE 0
362 #define SERIES_COLUMN_START 1
363 #define SERIES_COLUMN_STOP  2
364 #define SERIES_COLUMN_STEP  3
365 
366   rc = sqlite3_declare_vtab(db,
367      "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
368   if( rc==SQLITE_OK ){
369     pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
370     if( pNew==0 ) return SQLITE_NOMEM;
371     memset(pNew, 0, sizeof(*pNew));
372   }
373   return rc;
374 }
375 
376 /*
377 ** This method is the destructor for series_cursor objects.
378 */
379 static int seriesDisconnect(sqlite3_vtab *pVtab){
380   sqlite3_free(pVtab);
381   return SQLITE_OK;
382 }
383 
384 /*
385 ** Constructor for a new series_cursor object.
386 */
387 static int seriesOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
388   series_cursor *pCur;
389   pCur = sqlite3_malloc( sizeof(*pCur) );
390   if( pCur==0 ) return SQLITE_NOMEM;
391   memset(pCur, 0, sizeof(*pCur));
392   *ppCursor = &pCur->base;
393   return SQLITE_OK;
394 }
395 
396 /*
397 ** Destructor for a series_cursor.
398 */
399 static int seriesClose(sqlite3_vtab_cursor *cur){
400   sqlite3_free(cur);
401   return SQLITE_OK;
402 }
403 
404 
405 /*
406 ** Advance a series_cursor to its next row of output.
407 */
408 static int seriesNext(sqlite3_vtab_cursor *cur){
409   series_cursor *pCur = (series_cursor*)cur;
410   if( pCur->isDesc ){
411     pCur->iValue -= pCur->iStep;
412   }else{
413     pCur->iValue += pCur->iStep;
414   }
415   pCur->iRowid++;
416   return SQLITE_OK;
417 }
418 
419 /*
420 ** Return values of columns for the row at which the series_cursor
421 ** is currently pointing.
422 */
423 static int seriesColumn(
424   sqlite3_vtab_cursor *cur,   /* The cursor */
425   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
426   int i                       /* Which column to return */
427 ){
428   series_cursor *pCur = (series_cursor*)cur;
429   sqlite3_int64 x = 0;
430   switch( i ){
431     case SERIES_COLUMN_START:  x = pCur->mnValue; break;
432     case SERIES_COLUMN_STOP:   x = pCur->mxValue; break;
433     case SERIES_COLUMN_STEP:   x = pCur->iStep;   break;
434     default:                   x = pCur->iValue;  break;
435   }
436   sqlite3_result_int64(ctx, x);
437   return SQLITE_OK;
438 }
439 
440 /*
441 ** Return the rowid for the current row.  In this implementation, the
442 ** rowid is the same as the output value.
443 */
444 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
445   series_cursor *pCur = (series_cursor*)cur;
446   *pRowid = pCur->iRowid;
447   return SQLITE_OK;
448 }
449 
450 /*
451 ** Return TRUE if the cursor has been moved off of the last
452 ** row of output.
453 */
454 static int seriesEof(sqlite3_vtab_cursor *cur){
455   series_cursor *pCur = (series_cursor*)cur;
456   if( pCur->isDesc ){
457     return pCur->iValue < pCur->mnValue;
458   }else{
459     return pCur->iValue > pCur->mxValue;
460   }
461 }
462 
463 /* True to cause run-time checking of the start=, stop=, and/or step=
464 ** parameters.  The only reason to do this is for testing the
465 ** constraint checking logic for virtual tables in the SQLite core.
466 */
467 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
468 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
469 #endif
470 
471 /*
472 ** This method is called to "rewind" the series_cursor object back
473 ** to the first row of output.  This method is always called at least
474 ** once prior to any call to seriesColumn() or seriesRowid() or
475 ** seriesEof().
476 **
477 ** The query plan selected by seriesBestIndex is passed in the idxNum
478 ** parameter.  (idxStr is not used in this implementation.)  idxNum
479 ** is a bitmask showing which constraints are available:
480 **
481 **    1:    start=VALUE
482 **    2:    stop=VALUE
483 **    4:    step=VALUE
484 **
485 ** Also, if bit 8 is set, that means that the series should be output
486 ** in descending order rather than in ascending order.
487 **
488 ** This routine should initialize the cursor and position it so that it
489 ** is pointing at the first row, or pointing off the end of the table
490 ** (so that seriesEof() will return true) if the table is empty.
491 */
492 static int seriesFilter(
493   sqlite3_vtab_cursor *pVtabCursor,
494   int idxNum, const char *idxStr,
495   int argc, sqlite3_value **argv
496 ){
497   series_cursor *pCur = (series_cursor *)pVtabCursor;
498   int i = 0;
499   if( idxNum & 1 ){
500     pCur->mnValue = sqlite3_value_int64(argv[i++]);
501   }else{
502     pCur->mnValue = 0;
503   }
504   if( idxNum & 2 ){
505     pCur->mxValue = sqlite3_value_int64(argv[i++]);
506   }else{
507     pCur->mxValue = 0xffffffff;
508   }
509   if( idxNum & 4 ){
510     pCur->iStep = sqlite3_value_int64(argv[i++]);
511     if( pCur->iStep<1 ) pCur->iStep = 1;
512   }else{
513     pCur->iStep = 1;
514   }
515   if( idxNum & 8 ){
516     pCur->isDesc = 1;
517     pCur->iValue = pCur->mxValue;
518     if( pCur->iStep>0 ){
519       pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
520     }
521   }else{
522     pCur->isDesc = 0;
523     pCur->iValue = pCur->mnValue;
524   }
525   pCur->iRowid = 1;
526   return SQLITE_OK;
527 }
528 
529 /*
530 ** SQLite will invoke this method one or more times while planning a query
531 ** that uses the generate_series virtual table.  This routine needs to create
532 ** a query plan for each invocation and compute an estimated cost for that
533 ** plan.
534 **
535 ** In this implementation idxNum is used to represent the
536 ** query plan.  idxStr is unused.
537 **
538 ** The query plan is represented by bits in idxNum:
539 **
540 **  (1)  start = $value  -- constraint exists
541 **  (2)  stop = $value   -- constraint exists
542 **  (4)  step = $value   -- constraint exists
543 **  (8)  output in descending order
544 */
545 static int seriesBestIndex(
546   sqlite3_vtab *tab,
547   sqlite3_index_info *pIdxInfo
548 ){
549   int i;                 /* Loop over constraints */
550   int idxNum = 0;        /* The query plan bitmask */
551   int startIdx = -1;     /* Index of the start= constraint, or -1 if none */
552   int stopIdx = -1;      /* Index of the stop= constraint, or -1 if none */
553   int stepIdx = -1;      /* Index of the step= constraint, or -1 if none */
554   int nArg = 0;          /* Number of arguments that seriesFilter() expects */
555 
556   const struct sqlite3_index_constraint *pConstraint;
557   pConstraint = pIdxInfo->aConstraint;
558   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
559     if( pConstraint->usable==0 ) continue;
560     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
561     switch( pConstraint->iColumn ){
562       case SERIES_COLUMN_START:
563         startIdx = i;
564         idxNum |= 1;
565         break;
566       case SERIES_COLUMN_STOP:
567         stopIdx = i;
568         idxNum |= 2;
569         break;
570       case SERIES_COLUMN_STEP:
571         stepIdx = i;
572         idxNum |= 4;
573         break;
574     }
575   }
576   if( startIdx>=0 ){
577     pIdxInfo->aConstraintUsage[startIdx].argvIndex = ++nArg;
578     pIdxInfo->aConstraintUsage[startIdx].omit= !SQLITE_SERIES_CONSTRAINT_VERIFY;
579   }
580   if( stopIdx>=0 ){
581     pIdxInfo->aConstraintUsage[stopIdx].argvIndex = ++nArg;
582     pIdxInfo->aConstraintUsage[stopIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
583   }
584   if( stepIdx>=0 ){
585     pIdxInfo->aConstraintUsage[stepIdx].argvIndex = ++nArg;
586     pIdxInfo->aConstraintUsage[stepIdx].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
587   }
588   if( (idxNum & 3)==3 ){
589     /* Both start= and stop= boundaries are available.  This is the
590     ** the preferred case */
591     pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
592     pIdxInfo->estimatedRows = 1000;
593     if( pIdxInfo->nOrderBy==1 ){
594       if( pIdxInfo->aOrderBy[0].desc ) idxNum |= 8;
595       pIdxInfo->orderByConsumed = 1;
596     }
597   }else{
598     /* If either boundary is missing, we have to generate a huge span
599     ** of numbers.  Make this case very expensive so that the query
600     ** planner will work hard to avoid it. */
601     pIdxInfo->estimatedCost = (double)2147483647;
602     pIdxInfo->estimatedRows = 2147483647;
603   }
604   pIdxInfo->idxNum = idxNum;
605   return SQLITE_OK;
606 }
607 
608 /*
609 ** This following structure defines all the methods for the
610 ** generate_series virtual table.
611 */
612 static sqlite3_module seriesModule = {
613   0,                         /* iVersion */
614   0,                         /* xCreate */
615   seriesConnect,             /* xConnect */
616   seriesBestIndex,           /* xBestIndex */
617   seriesDisconnect,          /* xDisconnect */
618   0,                         /* xDestroy */
619   seriesOpen,                /* xOpen - open a cursor */
620   seriesClose,               /* xClose - close a cursor */
621   seriesFilter,              /* xFilter - configure scan constraints */
622   seriesNext,                /* xNext - advance a cursor */
623   seriesEof,                 /* xEof - check for end of scan */
624   seriesColumn,              /* xColumn - read data */
625   seriesRowid,               /* xRowid - read data */
626   0,                         /* xUpdate */
627   0,                         /* xBegin */
628   0,                         /* xSync */
629   0,                         /* xCommit */
630   0,                         /* xRollback */
631   0,                         /* xFindMethod */
632   0,                         /* xRename */
633 };
634 /* END the generate_series(START,END,STEP) implementation
635 *********************************************************************************/
636 
637 /*
638 ** Print sketchy documentation for this utility program
639 */
640 static void showHelp(void){
641   printf("Usage: %s [options] ?FILE...?\n", g.zArgv0);
642   printf(
643 "Read SQL text from FILE... (or from standard input if FILE... is omitted)\n"
644 "and then evaluate each block of SQL contained therein.\n"
645 "Options:\n"
646 "  --autovacuum          Enable AUTOVACUUM mode\n"
647 "  --database FILE       Use database FILE instead of an in-memory database\n"
648 "  --disable-lookaside   Turn off lookaside memory\n"
649 "  --heap SZ MIN         Memory allocator uses SZ bytes & min allocation MIN\n"
650 "  --help                Show this help text\n"
651 "  --lookaside N SZ      Configure lookaside for N slots of SZ bytes each\n"
652 "  --oom                 Run each test multiple times in a simulated OOM loop\n"
653 "  --pagesize N          Set the page size to N\n"
654 "  --pcache N SZ         Configure N pages of pagecache each of size SZ bytes\n"
655 "  -q                    Reduced output\n"
656 "  --quiet               Reduced output\n"
657 "  --scratch N SZ        Configure scratch memory for N slots of SZ bytes each\n"
658 "  --unique-cases FILE   Write all unique test cases to FILE\n"
659 "  --utf16be             Set text encoding to UTF-16BE\n"
660 "  --utf16le             Set text encoding to UTF-16LE\n"
661 "  -v                    Increased output\n"
662 "  --verbose             Increased output\n"
663   );
664 }
665 
666 /*
667 ** Return the value of a hexadecimal digit.  Return -1 if the input
668 ** is not a hex digit.
669 */
670 static int hexDigitValue(char c){
671   if( c>='0' && c<='9' ) return c - '0';
672   if( c>='a' && c<='f' ) return c - 'a' + 10;
673   if( c>='A' && c<='F' ) return c - 'A' + 10;
674   return -1;
675 }
676 
677 /*
678 ** Interpret zArg as an integer value, possibly with suffixes.
679 */
680 static int integerValue(const char *zArg){
681   sqlite3_int64 v = 0;
682   static const struct { char *zSuffix; int iMult; } aMult[] = {
683     { "KiB", 1024 },
684     { "MiB", 1024*1024 },
685     { "GiB", 1024*1024*1024 },
686     { "KB",  1000 },
687     { "MB",  1000000 },
688     { "GB",  1000000000 },
689     { "K",   1000 },
690     { "M",   1000000 },
691     { "G",   1000000000 },
692   };
693   int i;
694   int isNeg = 0;
695   if( zArg[0]=='-' ){
696     isNeg = 1;
697     zArg++;
698   }else if( zArg[0]=='+' ){
699     zArg++;
700   }
701   if( zArg[0]=='0' && zArg[1]=='x' ){
702     int x;
703     zArg += 2;
704     while( (x = hexDigitValue(zArg[0]))>=0 ){
705       v = (v<<4) + x;
706       zArg++;
707     }
708   }else{
709     while( ISDIGIT(zArg[0]) ){
710       v = v*10 + zArg[0] - '0';
711       zArg++;
712     }
713   }
714   for(i=0; i<sizeof(aMult)/sizeof(aMult[0]); i++){
715     if( sqlite3_stricmp(aMult[i].zSuffix, zArg)==0 ){
716       v *= aMult[i].iMult;
717       break;
718     }
719   }
720   if( v>0x7fffffff ) abendError("parameter too large - max 2147483648");
721   return (int)(isNeg? -v : v);
722 }
723 
724 /* Return the current wall-clock time */
725 static sqlite3_int64 timeOfDay(void){
726   static sqlite3_vfs *clockVfs = 0;
727   sqlite3_int64 t;
728   if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0);
729   if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){
730     clockVfs->xCurrentTimeInt64(clockVfs, &t);
731   }else{
732     double r;
733     clockVfs->xCurrentTime(clockVfs, &r);
734     t = (sqlite3_int64)(r*86400000.0);
735   }
736   return t;
737 }
738 
739 int main(int argc, char **argv){
740   char *zIn = 0;                /* Input text */
741   int nAlloc = 0;               /* Number of bytes allocated for zIn[] */
742   int nIn = 0;                  /* Number of bytes of zIn[] used */
743   size_t got;                   /* Bytes read from input */
744   int rc = SQLITE_OK;           /* Result codes from API functions */
745   int i;                        /* Loop counter */
746   int iNext;                    /* Next block of SQL */
747   sqlite3 *db;                  /* Open database */
748   char *zErrMsg = 0;            /* Error message returned from sqlite3_exec() */
749   const char *zEncoding = 0;    /* --utf16be or --utf16le */
750   int nHeap = 0, mnHeap = 0;    /* Heap size from --heap */
751   int nLook = 0, szLook = 0;    /* --lookaside configuration */
752   int nPCache = 0, szPCache = 0;/* --pcache configuration */
753   int nScratch = 0, szScratch=0;/* --scratch configuration */
754   int pageSize = 0;             /* Desired page size.  0 means default */
755   void *pHeap = 0;              /* Allocated heap space */
756   void *pLook = 0;              /* Allocated lookaside space */
757   void *pPCache = 0;            /* Allocated storage for pcache */
758   void *pScratch = 0;           /* Allocated storage for scratch */
759   int doAutovac = 0;            /* True for --autovacuum */
760   char *zSql;                   /* SQL to run */
761   char *zToFree = 0;            /* Call sqlite3_free() on this afte running zSql */
762   int verboseFlag = 0;          /* --verbose or -v flag */
763   int quietFlag = 0;            /* --quiet or -q flag */
764   int nTest = 0;                /* Number of test cases run */
765   int multiTest = 0;            /* True if there will be multiple test cases */
766   int lastPct = -1;             /* Previous percentage done output */
767   sqlite3 *dataDb = 0;          /* Database holding compacted input data */
768   sqlite3_stmt *pStmt = 0;      /* Statement to insert testcase into dataDb */
769   const char *zDataOut = 0;     /* Write compacted data to this output file */
770   int nHeader = 0;              /* Bytes of header comment text on input file */
771   int oomFlag = 0;              /* --oom */
772   int oomCnt = 0;               /* Counter for the OOM loop */
773   char zErrBuf[200];            /* Space for the error message */
774   const char *zFailCode;        /* Value of the TEST_FAILURE environment var */
775   const char *zPrompt;          /* Initial prompt when large-file fuzzing */
776   int nInFile = 0;              /* Number of input files to read */
777   char **azInFile = 0;          /* Array of input file names */
778   int jj;                       /* Loop counter for azInFile[] */
779   sqlite3_int64 iBegin;         /* Start time for the whole program */
780   sqlite3_int64 iStart, iEnd;   /* Start and end-times for a test case */
781   const char *zDbName = 0;      /* Name of an on-disk database file to open */
782 
783   iBegin = timeOfDay();
784   sqlite3_shutdown();
785   zFailCode = getenv("TEST_FAILURE");
786   g.zArgv0 = argv[0];
787   zPrompt = "<stdin>";
788   for(i=1; i<argc; i++){
789     const char *z = argv[i];
790     if( z[0]=='-' ){
791       z++;
792       if( z[0]=='-' ) z++;
793       if( strcmp(z,"autovacuum")==0 ){
794         doAutovac = 1;
795       }else
796       if( strcmp(z,"database")==0 ){
797         if( i>=argc-1 ) abendError("missing argument on %s\n", argv[i]);
798         zDbName = argv[i+1];
799         i += 1;
800       }else
801       if( strcmp(z,"disable-lookaside")==0 ){
802         nLook = 1;
803         szLook = 0;
804       }else
805       if( strcmp(z, "f")==0 && i+1<argc ){
806         i++;
807         goto addNewInFile;
808       }else
809       if( strcmp(z,"heap")==0 ){
810         if( i>=argc-2 ) abendError("missing arguments on %s\n", argv[i]);
811         nHeap = integerValue(argv[i+1]);
812         mnHeap = integerValue(argv[i+2]);
813         i += 2;
814       }else
815       if( strcmp(z,"help")==0 ){
816         showHelp();
817         return 0;
818       }else
819       if( strcmp(z,"lookaside")==0 ){
820         if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
821         nLook = integerValue(argv[i+1]);
822         szLook = integerValue(argv[i+2]);
823         i += 2;
824       }else
825       if( strcmp(z,"oom")==0 ){
826         oomFlag = 1;
827       }else
828       if( strcmp(z,"pagesize")==0 ){
829         if( i>=argc-1 ) abendError("missing argument on %s", argv[i]);
830         pageSize = integerValue(argv[++i]);
831       }else
832       if( strcmp(z,"pcache")==0 ){
833         if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
834         nPCache = integerValue(argv[i+1]);
835         szPCache = integerValue(argv[i+2]);
836         i += 2;
837       }else
838       if( strcmp(z,"quiet")==0 || strcmp(z,"q")==0 ){
839         quietFlag = 1;
840         verboseFlag = 0;
841       }else
842       if( strcmp(z,"scratch")==0 ){
843         if( i>=argc-2 ) abendError("missing arguments on %s", argv[i]);
844         nScratch = integerValue(argv[i+1]);
845         szScratch = integerValue(argv[i+2]);
846         i += 2;
847       }else
848       if( strcmp(z, "unique-cases")==0 ){
849         if( i>=argc-1 ) abendError("missing arguments on %s", argv[i]);
850         if( zDataOut ) abendError("only one --minimize allowed");
851         zDataOut = argv[++i];
852       }else
853       if( strcmp(z,"utf16le")==0 ){
854         zEncoding = "utf16le";
855       }else
856       if( strcmp(z,"utf16be")==0 ){
857         zEncoding = "utf16be";
858       }else
859       if( strcmp(z,"verbose")==0 || strcmp(z,"v")==0 ){
860         quietFlag = 0;
861         verboseFlag = 1;
862       }else
863       {
864         abendError("unknown option: %s", argv[i]);
865       }
866     }else{
867       addNewInFile:
868       nInFile++;
869       azInFile = realloc(azInFile, sizeof(azInFile[0])*nInFile);
870       if( azInFile==0 ) abendError("out of memory");
871       azInFile[nInFile-1] = argv[i];
872     }
873   }
874 
875   /* Do global SQLite initialization */
876   sqlite3_config(SQLITE_CONFIG_LOG, verboseFlag ? shellLog : shellLogNoop, 0);
877   if( nHeap>0 ){
878     pHeap = malloc( nHeap );
879     if( pHeap==0 ) fatalError("cannot allocate %d-byte heap\n", nHeap);
880     rc = sqlite3_config(SQLITE_CONFIG_HEAP, pHeap, nHeap, mnHeap);
881     if( rc ) abendError("heap configuration failed: %d\n", rc);
882   }
883   if( oomFlag ){
884     sqlite3_config(SQLITE_CONFIG_GETMALLOC, &g.sOrigMem);
885     g.sOomMem = g.sOrigMem;
886     g.sOomMem.xMalloc = oomMalloc;
887     g.sOomMem.xRealloc = oomRealloc;
888     sqlite3_config(SQLITE_CONFIG_MALLOC, &g.sOomMem);
889   }
890   if( nLook>0 ){
891     sqlite3_config(SQLITE_CONFIG_LOOKASIDE, 0, 0);
892     if( szLook>0 ){
893       pLook = malloc( nLook*szLook );
894       if( pLook==0 ) fatalError("out of memory");
895     }
896   }
897   if( nScratch>0 && szScratch>0 ){
898     pScratch = malloc( nScratch*(sqlite3_int64)szScratch );
899     if( pScratch==0 ) fatalError("cannot allocate %lld-byte scratch",
900                                  nScratch*(sqlite3_int64)szScratch);
901     rc = sqlite3_config(SQLITE_CONFIG_SCRATCH, pScratch, szScratch, nScratch);
902     if( rc ) abendError("scratch configuration failed: %d\n", rc);
903   }
904   if( nPCache>0 && szPCache>0 ){
905     pPCache = malloc( nPCache*(sqlite3_int64)szPCache );
906     if( pPCache==0 ) fatalError("cannot allocate %lld-byte pcache",
907                                  nPCache*(sqlite3_int64)szPCache);
908     rc = sqlite3_config(SQLITE_CONFIG_PAGECACHE, pPCache, szPCache, nPCache);
909     if( rc ) abendError("pcache configuration failed: %d", rc);
910   }
911 
912   /* If the --unique-cases option was supplied, open the database that will
913   ** be used to gather unique test cases.
914   */
915   if( zDataOut ){
916     rc = sqlite3_open(":memory:", &dataDb);
917     if( rc ) abendError("cannot open :memory: database");
918     rc = sqlite3_exec(dataDb,
919           "CREATE TABLE testcase(sql BLOB PRIMARY KEY, tm) WITHOUT ROWID;",0,0,0);
920     if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
921     rc = sqlite3_prepare_v2(dataDb,
922           "INSERT OR IGNORE INTO testcase(sql,tm)VALUES(?1,?2)",
923           -1, &pStmt, 0);
924     if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
925   }
926 
927   /* Initialize the input buffer used to hold SQL text */
928   if( nInFile==0 ) nInFile = 1;
929   nAlloc = 1000;
930   zIn = malloc(nAlloc);
931   if( zIn==0 ) fatalError("out of memory");
932 
933   /* Loop over all input files */
934   for(jj=0; jj<nInFile; jj++){
935 
936     /* Read the complete content of the next input file into zIn[] */
937     FILE *in;
938     if( azInFile ){
939       int j, k;
940       in = fopen(azInFile[jj],"rb");
941       if( in==0 ){
942         abendError("cannot open %s for reading", azInFile[jj]);
943       }
944       zPrompt = azInFile[jj];
945       for(j=k=0; zPrompt[j]; j++) if( zPrompt[j]=='/' ) k = j+1;
946       zPrompt += k;
947     }else{
948       in = stdin;
949       zPrompt = "<stdin>";
950     }
951     while( !feof(in) ){
952       got = fread(zIn+nIn, 1, nAlloc-nIn-1, in);
953       nIn += (int)got;
954       zIn[nIn] = 0;
955       if( got==0 ) break;
956       if( nAlloc - nIn - 1 < 100 ){
957         nAlloc += nAlloc+1000;
958         zIn = realloc(zIn, nAlloc);
959         if( zIn==0 ) fatalError("out of memory");
960       }
961     }
962     if( in!=stdin ) fclose(in);
963     lastPct = -1;
964 
965     /* Skip initial lines of the input file that begin with "#" */
966     for(i=0; i<nIn; i=iNext+1){
967       if( zIn[i]!='#' ) break;
968       for(iNext=i+1; iNext<nIn && zIn[iNext]!='\n'; iNext++){}
969     }
970     nHeader = i;
971 
972     /* Process all test cases contained within the input file.
973     */
974     for(; i<nIn; i=iNext, nTest++, g.zTestName[0]=0){
975       char cSaved;
976       if( strncmp(&zIn[i], "/****<",6)==0 ){
977         char *z = strstr(&zIn[i], ">****/");
978         if( z ){
979           z += 6;
980           sqlite3_snprintf(sizeof(g.zTestName), g.zTestName, "%.*s",
981                            (int)(z-&zIn[i]) - 12, &zIn[i+6]);
982           if( verboseFlag ){
983             printf("%.*s\n", (int)(z-&zIn[i]), &zIn[i]);
984             fflush(stdout);
985           }
986           i += (int)(z-&zIn[i]);
987           multiTest = 1;
988         }
989       }
990       for(iNext=i; iNext<nIn && strncmp(&zIn[iNext],"/****<",6)!=0; iNext++){}
991       cSaved = zIn[iNext];
992       zIn[iNext] = 0;
993 
994 
995       /* Print out the SQL of the next test case is --verbose is enabled
996       */
997       zSql = &zIn[i];
998       if( verboseFlag ){
999         printf("INPUT (offset: %d, size: %d): [%s]\n",
1000                 i, (int)strlen(&zIn[i]), &zIn[i]);
1001       }else if( multiTest && !quietFlag ){
1002         if( oomFlag ){
1003           printf("%s\n", g.zTestName);
1004         }else{
1005           int pct = (10*iNext)/nIn;
1006           if( pct!=lastPct ){
1007             if( lastPct<0 ) printf("%s:", zPrompt);
1008             printf(" %d%%", pct*10);
1009             lastPct = pct;
1010           }
1011         }
1012       }else if( nInFile>1 ){
1013         printf("%s\n", zPrompt);
1014       }
1015       fflush(stdout);
1016 
1017       /* Run the next test case.  Run it multiple times in --oom mode
1018       */
1019       if( oomFlag ){
1020         oomCnt = g.iOomCntdown = 1;
1021         g.nOomFault = 0;
1022         g.bOomOnce = 1;
1023         if( verboseFlag ){
1024           printf("Once.%d\n", oomCnt);
1025           fflush(stdout);
1026         }
1027       }else{
1028         oomCnt = 0;
1029       }
1030       do{
1031         if( zDbName ){
1032           rc = sqlite3_open_v2(zDbName, &db, SQLITE_OPEN_READWRITE, 0);
1033           if( rc!=SQLITE_OK ){
1034             abendError("Cannot open database file %s", zDbName);
1035           }
1036         }else{
1037           rc = sqlite3_open_v2(
1038             "main.db", &db,
1039             SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY,
1040             0);
1041           if( rc!=SQLITE_OK ){
1042             abendError("Unable to open the in-memory database");
1043           }
1044         }
1045         if( pLook ){
1046           rc = sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE,pLook,szLook,nLook);
1047           if( rc!=SQLITE_OK ) abendError("lookaside configuration filed: %d", rc);
1048         }
1049     #ifndef SQLITE_OMIT_TRACE
1050         sqlite3_trace(db, verboseFlag ? traceCallback : traceNoop, 0);
1051     #endif
1052         sqlite3_create_function(db, "eval", 1, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
1053         sqlite3_create_function(db, "eval", 2, SQLITE_UTF8, 0, sqlEvalFunc, 0, 0);
1054         sqlite3_create_module(db, "generate_series", &seriesModule, 0);
1055         sqlite3_limit(db, SQLITE_LIMIT_LENGTH, 1000000);
1056         if( zEncoding ) sqlexec(db, "PRAGMA encoding=%s", zEncoding);
1057         if( pageSize ) sqlexec(db, "PRAGMA pagesize=%d", pageSize);
1058         if( doAutovac ) sqlexec(db, "PRAGMA auto_vacuum=FULL");
1059         iStart = timeOfDay();
1060         g.bOomEnable = 1;
1061         if( verboseFlag ){
1062           zErrMsg = 0;
1063           rc = sqlite3_exec(db, zSql, execCallback, 0, &zErrMsg);
1064           if( zErrMsg ){
1065             sqlite3_snprintf(sizeof(zErrBuf),zErrBuf,"%z", zErrMsg);
1066             zErrMsg = 0;
1067           }
1068         }else {
1069           rc = sqlite3_exec(db, zSql, execNoop, 0, 0);
1070         }
1071         g.bOomEnable = 0;
1072         iEnd = timeOfDay();
1073         rc = sqlite3_close(db);
1074         if( rc ){
1075           abendError("sqlite3_close() failed with rc=%d", rc);
1076         }
1077         if( !zDataOut && sqlite3_memory_used()>0 ){
1078           abendError("memory in use after close: %lld bytes",sqlite3_memory_used());
1079         }
1080         if( oomFlag ){
1081           /* Limit the number of iterations of the OOM loop to OOM_MAX.  If the
1082           ** first pass (single failure) exceeds 2/3rds of OOM_MAX this skip the
1083           ** second pass (continuous failure after first) completely. */
1084           if( g.nOomFault==0 || oomCnt>OOM_MAX ){
1085             if( g.bOomOnce && oomCnt<=(OOM_MAX*2/3) ){
1086               oomCnt = g.iOomCntdown = 1;
1087               g.bOomOnce = 0;
1088             }else{
1089               oomCnt = 0;
1090             }
1091           }else{
1092             g.iOomCntdown = ++oomCnt;
1093             g.nOomFault = 0;
1094           }
1095           if( oomCnt ){
1096             if( verboseFlag ){
1097               printf("%s.%d\n", g.bOomOnce ? "Once" : "Multi", oomCnt);
1098               fflush(stdout);
1099             }
1100             nTest++;
1101           }
1102         }
1103       }while( oomCnt>0 );
1104 
1105       /* Store unique test cases in the in the dataDb database if the
1106       ** --unique-cases flag is present
1107       */
1108       if( zDataOut ){
1109         sqlite3_bind_blob(pStmt, 1, &zIn[i], iNext-i, SQLITE_STATIC);
1110         sqlite3_bind_int64(pStmt, 2, iEnd - iStart);
1111         rc = sqlite3_step(pStmt);
1112         if( rc!=SQLITE_DONE ) abendError("%s", sqlite3_errmsg(dataDb));
1113         sqlite3_reset(pStmt);
1114       }
1115 
1116       /* Free the SQL from the current test case
1117       */
1118       if( zToFree ){
1119         sqlite3_free(zToFree);
1120         zToFree = 0;
1121       }
1122       zIn[iNext] = cSaved;
1123 
1124       /* Show test-case results in --verbose mode
1125       */
1126       if( verboseFlag ){
1127         printf("RESULT-CODE: %d\n", rc);
1128         if( zErrMsg ){
1129           printf("ERROR-MSG: [%s]\n", zErrBuf);
1130         }
1131         fflush(stdout);
1132       }
1133 
1134       /* Simulate an error if the TEST_FAILURE environment variable is "5".
1135       ** This is used to verify that automated test script really do spot
1136       ** errors that occur in this test program.
1137       */
1138       if( zFailCode ){
1139         if( zFailCode[0]=='5' && zFailCode[1]==0 ){
1140           abendError("simulated failure");
1141         }else if( zFailCode[0]!=0 ){
1142           /* If TEST_FAILURE is something other than 5, just exit the test
1143           ** early */
1144           printf("\nExit early due to TEST_FAILURE being set");
1145           break;
1146         }
1147       }
1148     }
1149     if( !verboseFlag && multiTest && !quietFlag && !oomFlag ) printf("\n");
1150   }
1151 
1152   /* Report total number of tests run
1153   */
1154   if( nTest>1 && !quietFlag ){
1155     sqlite3_int64 iElapse = timeOfDay() - iBegin;
1156     printf("%s: 0 errors out of %d tests in %d.%03d seconds\nSQLite %s %s\n",
1157            g.zArgv0, nTest, (int)(iElapse/1000), (int)(iElapse%1000),
1158            sqlite3_libversion(), sqlite3_sourceid());
1159   }
1160 
1161   /* Write the unique test cases if the --unique-cases flag was used
1162   */
1163   if( zDataOut ){
1164     int n = 0;
1165     FILE *out = fopen(zDataOut, "wb");
1166     if( out==0 ) abendError("cannot open %s for writing", zDataOut);
1167     if( nHeader>0 ) fwrite(zIn, nHeader, 1, out);
1168     sqlite3_finalize(pStmt);
1169     rc = sqlite3_prepare_v2(dataDb, "SELECT sql, tm FROM testcase ORDER BY tm, sql",
1170                             -1, &pStmt, 0);
1171     if( rc ) abendError("%s", sqlite3_errmsg(dataDb));
1172     while( sqlite3_step(pStmt)==SQLITE_ROW ){
1173       fprintf(out,"/****<%d:%dms>****/", ++n, sqlite3_column_int(pStmt,1));
1174       fwrite(sqlite3_column_blob(pStmt,0),sqlite3_column_bytes(pStmt,0),1,out);
1175     }
1176     fclose(out);
1177     sqlite3_finalize(pStmt);
1178     sqlite3_close(dataDb);
1179   }
1180 
1181   /* Clean up and exit.
1182   */
1183   free(azInFile);
1184   free(zIn);
1185   free(pHeap);
1186   free(pLook);
1187   free(pScratch);
1188   free(pPCache);
1189   return 0;
1190 }
1191